Click here to Skip to main content
11,478,896 members (58,763 online)
Click here to Skip to main content

An introduction to System.Lazy- Dotnet 4.0

, 27 Oct 2010 CPOL 15.1K 88 4
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 Pin
Batzen28-Oct-10 2:51
memberBatzen28-Oct-10 2:51 
GeneralMy vote of 1 Pin
SledgeHammer0127-Oct-10 8:23
memberSledgeHammer0127-Oct-10 8:23 
GeneralMy vote of 1 Pin
Argyle4Ever27-Oct-10 5:25
memberArgyle4Ever27-Oct-10 5:25 
GeneralMy vote of 1 Pin
Selvin26-Oct-10 5:54
memberSelvin26-Oct-10 5:54 
GeneralMy vote of 2 Pin
Abhishek Sur25-Oct-10 10:10
mvpAbhishek Sur25-Oct-10 10:10 
GeneralMy vote of 1 Pin
Sacha Barber25-Oct-10 6:18
mvpSacha Barber25-Oct-10 6:18 
GeneralRe: My vote of 1 Pin
jahmani25-Oct-10 9:42
memberjahmani25-Oct-10 9:42 
QuestionRe: My vote of 1 Pin
Paul Selormey25-Oct-10 9:54
memberPaul Selormey25-Oct-10 9:54 
AnswerRe: My vote of 1 Pin
jahmani25-Oct-10 11:47
memberjahmani25-Oct-10 11:47 
GeneralRe: My vote of 1 Pin
Paul Selormey25-Oct-10 9:58
memberPaul Selormey25-Oct-10 9:58 
GeneralRe: My vote of 1 Pin
Sacha Barber25-Oct-10 20:55
mvpSacha Barber25-Oct-10 20:55 
GeneralRe: My vote of 1 Pin
Paul Selormey25-Oct-10 21:42
memberPaul Selormey25-Oct-10 21:42 
GeneralRe: My vote of 1 Pin
Sacha Barber25-Oct-10 22:48
mvpSacha Barber25-Oct-10 22: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 | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 27 Oct 2010
Article Copyright 2010 by Niladri_Biswas
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid