I would like to do lazy initialization of the below call. I know the type of T while constructing the object.
T facade = (T)Activator.CreateInstance(typeof(T), param);
Is there a way to achieve this?
You could subclass Lazy<T>
, like this:
public class LazyActivator<T> : Lazy<T>
{
public LazyActivator(params object[] args) : base(() => (T)Activator.CreateInstance(typeof(T), args))
{
}
}
then:
LazyActivator<List<int>> lazyList = new LazyActivator<List<int>>(5);
and if you need the List<int>
(that has Capacity == 5
)
List<int> list = lazyList.Value;