Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

An introduction to System.Lazy- Dotnet 4.0

0.00/5 (No votes)
27 Oct 2010 1  
This article introduces the System.Lazy and its usefulness

Introduction

Object creation is always expensive. It is better to create object when it is actually needed to do so. Otherwise, unnecessary memory allocation on the heap will cause a memory load. Lazy<T> which is defined in the mscorlib assembly and belongs to System namespace, ensures that object is created only when it is needed.

Using the code

Consider the below program

static void Main(string[] args)
{           

  var lazyObject = new Lazy<list<expandoobject>>
  (
    () =>
    { 
      List<expandoobject> expandoList = new List<expandoobject>();
      //Writing to Expando Collection
       for (int i = 3; i-- > 1; )
       {
         dynamic dynObject = new ExpandoObject();                       
         dynObject.Prop1 = GetValue(i);                       
         expandoList.Add(dynObject);
       }
         return expandoList;
      }
);

Console.WriteLine("Enter a value. 1 to proceed");
var read = Console.ReadLine();
List<expandoobject> expandoObj = null;

if (read == "1")
{
  //If the value is not created 
  if (!lazyObject.IsValueCreated)
  //Gets the lazily initialized value of the current Lazy<list<expandoobject>> 
  //instance.
  expandoObj = lazyObject.Value;
  //Read the values once the object is initialize
  if (expandoObj != null)
  {
      Console.WriteLine(Environment.NewLine);
      Console.WriteLine("The values are:");
      foreach (dynamic d in expandoObj) 
      Console.WriteLine(d.Prop1);
  }
 
 }
}

The GetValue method is as under

private static string GetValue(int i)
{
  Dictionary<int,> dict = new Dictionary<int,>();
  dict.Add(1, "Niladri");
  dict.Add(2, "Arina");
  return dict[i];
}

Let us go step by step as what we are doing here

Console.WriteLine("Enter a value. 1 to proceed");
var read = Console.ReadLine();

if (read == "1")
{
   // do something
}

This code piece is pretty understandable. We are checking whether the user has enter 1 to proceed further.

List<expandoobject> expandoObj = null;
//If the value is not created 
if (!lazyObject.IsValueCreated)
//Gets the lazily initialized value of the current Lazy<list<expandoobject>> 
//instance.
expandoObj = lazyObject.Value;

The method signature of IsValueCreated is

public bool IsValueCreated { get; }

It is a readonly property and indicates whether a value has been created for this System.Lazy<t>(in our case Lazy<list<expandoobject>>)instance.

If the value is not created at this point of time then by using the "Value" property of the Lazy<t>, we lazily initialize value of the Lazy<list<expandoobject>> instance. In other words, we call the constructor of our ExpandoObject class.

var lazyObject = new Lazy<list<expandoobject>>
 (
   () =>
   { 
      List<expandoobject> expandoList = new List<expandoobject>();
      //Writing to Expando Collection
      for (int i = 3; i-- > 1; )
      {
         dynamic dynObject = new ExpandoObject();                       
         dynObject.Prop1 = GetValue(i);                       
         expandoList.Add(dynObject);
      }
  return expandoList;
});

This piece of code is simple to understand as we have created a Property name as "Prop1" in the ExpandoObject and have added some value.

Next once the object is initialized, we should read the value

if (expandoObj != null)
{
  Console.WriteLine(Environment.NewLine);
  Console.WriteLine("The values are:");
  foreach (dynamic d in expandoObj) 
  Console.WriteLine(d.Prop1);
}

The output of the program is

LazyInitializers/1.jpg

The value reading can also be done by using

if (lazyObject.IsValueCreated)
{
  Console.WriteLine("The values are:");
  lazyObject.Value.ForEach(i => Console.WriteLine((i as dynamic).Prop1));
}

Conclusion

Here we have seen how Lazy helps us in creating object in an adhoc manner. Hope this will help in understanding the concept of Lazy<t>.

Comments on the topic are highly appreciated for the improvement of the topic.

Thanks for reading the article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here