to delay the creation of a large or resource-intensive object or perform a resource-in...">

Using Lazy <T>

Like on MSDN :

"Use an instance of Lazy<T> to delay the creation of a large or resource-intensive object or perform a resource-intensive task, especially if such creation or execution may not occur during the lifetime of the program.

For factory -pattern, I could use Lazy<T> to create instances instead of Activator.CreateInstance .

returning

 new Lazy<T>().value 

sort of:

 return Lazy<IFactoryInstance>(() => new Car()).Value; 

which gives me the ability to initialize an instance of an object in various ways for each type / instance, etc.

according to the method

But I have my doubts when reading text from MSDN. What is good practice for similar code? And why not use Lazy<T> ?

+4
source share
1 answer

The Lazy<T> and Activator.CreateInstance functions have completely different goals.

  • Lazy<T> : Used to create initialized delay values ​​once and only once. I disagree with the definition of an MSDN resource and simply replace it with "Used to create costly types on demand versus initialization."
  • Activator.CreateInstance : used to instantiate instances based on runtime information

The Lazy<T> type alone is not suitable for the factory pattern, because it is useful for creating a single instance (not many).

+5
source

All Articles