Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / C# 4.0

An introduction to System.Lazy- Dotnet 4.0

Rate me:
Please Sign up or sign in to vote.
1.40/5 (11 votes)
26 Oct 2010CPOL1 min read 29.4K   4   13
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

C#
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

C#
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

C#
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.

C#
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

C#
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.

C#
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

C#
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<t> 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)



Comments and Discussions

 
GeneralMy vote of 1 Pin
Batzen28-Oct-10 1:51
Batzen28-Oct-10 1:51 
GeneralMy vote of 1 Pin
SledgeHammer0127-Oct-10 7:23
SledgeHammer0127-Oct-10 7:23 
GeneralMy vote of 1 Pin
Argyle4Ever27-Oct-10 4:25
Argyle4Ever27-Oct-10 4:25 
GeneralMy vote of 1 Pin
Selvin26-Oct-10 4:54
Selvin26-Oct-10 4:54 
GeneralMy vote of 2 Pin
Abhishek Sur25-Oct-10 9:10
professionalAbhishek Sur25-Oct-10 9:10 
GeneralMy vote of 1 Pin
Sacha Barber25-Oct-10 5:18
Sacha Barber25-Oct-10 5:18 
GeneralRe: My vote of 1 Pin
jahmani25-Oct-10 8:42
jahmani25-Oct-10 8:42 
QuestionRe: My vote of 1 Pin
Paul Selormey25-Oct-10 8:54
Paul Selormey25-Oct-10 8:54 
AnswerRe: My vote of 1 Pin
jahmani25-Oct-10 10:47
jahmani25-Oct-10 10:47 
GeneralRe: My vote of 1 Pin
Paul Selormey25-Oct-10 8:58
Paul Selormey25-Oct-10 8:58 
GeneralRe: My vote of 1 Pin
Sacha Barber25-Oct-10 19:55
Sacha Barber25-Oct-10 19:55 
GeneralRe: My vote of 1 Pin
Paul Selormey25-Oct-10 20:42
Paul Selormey25-Oct-10 20:42 
GeneralRe: My vote of 1 Pin
Sacha Barber25-Oct-10 21:48
Sacha Barber25-Oct-10 21:48 
Certainly aint boring, very challenging to get that sort of thing actually.
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue

My Blog : sachabarber.net

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

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