Caspar Kleijne
Caspar Kleijne

Reputation: 21864

Usage of Lazy<T> vs. Activator.CreateInstance?

As on MSDN:

"Use an instance of Lazy<T> to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program."

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

by returning a

new Lazy<T>().value

something like:

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

that gives me the ability to initialize the object-instance in a different ways per type/instance etc. from a method.

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

Upvotes: 4

Views: 1364

Answers (1)

JaredPar
JaredPar

Reputation: 754695

The Lazy<T> type and Activator.CreateInstance function have very different purposes.

  • Lazy<T>: Used to create delay initialized values once and only once. I disagree with MSDN's definition of resource intensive and simply replace it with "Used to create expensive types on demand vs. on initialization".
  • Activator.CreateInstance: Used to create type instances based on runtime information

The Lazy<T> type in itself is not suitable for a factory pattern because it's useful for creating a single instance (not many).

Upvotes: 5

Related Questions