Search code examples
c#lazy-initialization

Lazy initialization of an object using reflection


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?


Solution

  • 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;