return new Lazy(() => new T()); /* Lazy initialization of objects in C# */

We should try to initialize objects when we need it otherwise the objects will reside in the memory. Probably it won't matter when the object is not that expensive otherwise it really matters. So if we could use something which give us the opportunity to initialize objects only when we need it or probably Singleton pattern or something like this. In .NET 4.0, there is new feature which will do the job for us. That feature is Lazy<T>, following code block will show the use of it,
static Lazy<T> LazyLoader<T>() where T : new()
{
    return new Lazy<T>(() => new T());
}
 
static Lazy<T> LazyLoader<T>(Func<T> lazyInitialisationBlock) where T : new()
{
    return new Lazy<T>(lazyInitialisationBlock);
}
 
static List<string> InitialisationBlock()
{
    return new List<string> { "One""Two" };
}
Usage of the above code,
static void Main(string[] args)
{
   Lazy<ClassForLazyLoad> loader = LazyLoader<ClassForLazyLoad>();
   Console.WriteLine("{0}", loader.Value.Name);
   Lazy<List<string>> listLoader = LazyLoader<List<string>>(InitialisationBlock);
   Console.WriteLine("{0}", ReferenceEquals(listLoader, null) ? "Loading hasn't been finished yet" : "Loading has been finished");
   Array.ForEach(listLoader.Value.ToArray(), item => Console.WriteLine(item.ToString()));
}
related classes,
public class ClassForLazyLoad
{
   public string Name { get { return GetType().FullName; } }
}

No comments:

Post a Comment