📜 ⬆️ ⬇️

Lazy : Constructing Objects On Demand in .NET 4.0

I like it when I find new parts of the functionality in the .NET framework. These are all the great things that get all the love and acceptance at conferences and in magazines.

Lazy <T> is just one of those.

Let's imagine that you are writing an application and in some scenarios, but not in the rest, you need a specific object. In addition, suppose that the creation and use of this object is very expensive. You do not want to create it every time your application starts. You want this object to be created only when you need it.

Of course, you can figure it out yourself, but Lazy <T> makes it easier. You simply create a lazy wrapper on a costly object:
')
Lazy< ExpensiveResource > ownedResource = new Lazy< ExpensiveResource >();

You can simply refer to "ownedResource.Value" to get to this expensive object. The first time you access ownedResource.Value, expensive resources are allocated, but not before.

Lazy <T> also has a boolean property called IsValueCreated, which you can check to see if an object was created in the Value property. This can be useful when you need to store information from an expensive resource, but only if it will be used.

Support for types without default constructors


Lazy <T> does not impose a restriction on the availability of new (). You can use Lazy <T> for types that need to be created using other constructors and even factory methods. The second constructor defines a delegate Func <T> that returns a new expensive resource:

Lazy< ExpensiveResource > ownedResource = new Lazy< ExpensiveResource >(
() => new ExpensiveResource( "filename.data" ));


You can use this constructor to better control how the code will create a costly resource. Here I used another constructor, but you can use a factory method, an IoC container, or another method.

We live in a multi-core world.


Lazy <T> has two more constructors:

public Lazy( bool isThreadSafe);
public Lazy( Func <T> valueFactory, bool isThreadSafe);


These two constructors show that you are running in a multi-threaded environment, and lazy object creation must be synchronized. (Besides, this is an expensive resource. You don’t need several of them.)

It’s a simple type, but it’s one of those types that you’ll find useful again and again.

I'm glad it was added.

Tags: C #, .NET General, C # General, DevCenterPosts

Source: https://habr.com/ru/post/76177/


All Articles