Back
Close

Using Lazy class in C#

gpeipman
5,946 views

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.

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);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants