Using Lazy<T> in C#

Scenarios when lazy initialization is suitable for using

Although Lazy keyword and functionality was introduced in .net framework 4.0, not many people are using. It is not something that was not possible to be done later, but now it is available only oin one line.

Basicaly what Lazy keyword enables is to create an instance only when it is invoked for the first time.

    public class Worker
    {
       private static Lazy<Object> Locker = new Lazy<Object>(() => new Object());

       public void DoSomething()
       {
           lock (Locker.Value)
           {
               //Do some thread-safe work
           }
       }
    }
    

 

When to use Lazy?

There are several scanraios where Lazy initialization is good to be used:

  1. When you do not want to initialize object which might never be used in code or will be used but only in certain cases. This means that instance will sit in memory although it might never be used
  2. Locking when doing multi threading in a code
  3. Implementing singletone pattern

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article