Click here to Skip to main content
Click here to Skip to main content

An introduction to System.Lazy- Dotnet 4.0

, 26 Oct 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 1 PinmemberBatzen28-Oct-10 1:51 
GeneralMy vote of 1 PinmemberSledgeHammer0127-Oct-10 7:23 
GeneralMy vote of 1 PinmemberArgyle4Ever27-Oct-10 4:25 
GeneralMy vote of 1 PinmemberSelvin26-Oct-10 4:54 
GeneralMy vote of 2 PinmvpAbhishek Sur25-Oct-10 9:10 
GeneralMy vote of 1 PinmvpSacha Barber25-Oct-10 5:18 
GeneralRe: My vote of 1 Pinmemberjahmani25-Oct-10 8:42 
QuestionRe: My vote of 1 PinmemberPaul Selormey25-Oct-10 8:54 
AnswerRe: My vote of 1 Pinmemberjahmani25-Oct-10 10:47 
GeneralRe: My vote of 1 PinmemberPaul Selormey25-Oct-10 8:58 
GeneralRe: My vote of 1 PinmvpSacha Barber25-Oct-10 19:55 
GeneralRe: My vote of 1 PinmemberPaul Selormey25-Oct-10 20:42 
GeneralRe: My vote of 1 PinmvpSacha Barber25-Oct-10 21:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 27 Oct 2010
Article Copyright 2010 by Niladri_Biswas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid