Using Lazy class in C#
gpeipman
25.6K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Using Lazy class in C#
System namespace in .NET Framework has Lazy class that provides us with basic mechanism for lazy loads. The idea of Lazy class is simple - initialize class with action that builds or gets lazy loaded value and when value is asked then run the action if lazy loading is not happened yet.
To demonstrate Lazy class let's see the example I created once. Before running the code, go through it and try to figure out in what order messages will appear.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
class Hello
{
static void Main(string[] args)
{
var lazyString = new Lazy<string>(
() =>
{
// Here you can do some complex processing
// and then return a value.
Console.WriteLine("Inside lazy loader");
return "Lazy loading!";
});
Console.Write("Is value created: ");
Console.WriteLine(lazyString.IsValueCreated);
var value = lazyString.Value;
Console.Write("Value: ");
Console.WriteLine(value);
Console.Write("Value again: ");
Console.WriteLine(lazyString.Value);
Console.Write("Is value created: ");
Console.WriteLine(lazyString.IsValueCreated);
}
}
Enter to Rename, Shift+Enter to Preview
References
- Using System.Lazy (Gunnar Peipman)
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content