IntroductionObject 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 codeConsider the below programstatic void Main(string[] args)
{ var lazyObject = new Lazy>
(
() =>
{
List expandoList = new List();
//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 expandoObj = null; if (read == "1")
{
//If the value is not created
if (!lazyObject.IsValueCreated)
//Gets the lazily initialized value of the current Lazy>
//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 underprivate static string GetValue(int i)
{
Dictionary dict = new Dictionary();
dict.Add(1, "Niladri");
dict.Add(2, "Arina");
return dict[i];
}Let us go step by step as what we are doing hereRead more: Codeproject
{ var lazyObject = new Lazy>
(
() =>
{
List expandoList = new List();
//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 expandoObj = null; if (read == "1")
{
//If the value is not created
if (!lazyObject.IsValueCreated)
//Gets the lazily initialized value of the current Lazy>
//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 underprivate static string GetValue(int i)
{
Dictionary dict = new Dictionary();
dict.Add(1, "Niladri");
dict.Add(2, "Arina");
return dict[i];
}Let us go step by step as what we are doing hereRead more: Codeproject
0 comments:
Post a Comment