Dilemma in calling constructor of generic class

c#, constructor, generics, initialization

Solution

Normally you would constrain the type `T` to a type that has a default constructor and call that. Then you'd have to add a method or property to be able to provide the value of `id` to the instance.

public static T LoadFromSharePoint<T>(Guid id)
    where T : new()     // <-- Constrain to types with a default constructor
{
    T value = new T();
    value.ID = id;
    return value;
}

Alternatively since you specify that you have to provide the `id` parameter through the constructor, you can invoke a parameterized constructor using reflection. You must be sure the type defines the constructor you want to invoke. You cannot constrain the generic type `T` to types that have a particular constructor other than the default constructor. (E.g. `where T : new(Guid)` does not work.)

For example, I know there is a constructor `new List<string>(int capacity)` on `List<T>`, which can be invoked like this:

var type = typeof(List<String>);
object list = Activator.CreateInstance(type, /* capacity */ 20);

Of course, you might want to do some casting (to `T`) afterwards.

Problem

I have this generic singleton that looks like this: ``` public class Cache<T> { private Dictionary<Guid, T> cachedBlocks; // Constructors and stuff, to mention this is a singleton public T GetCache(Guid id) { if (!cachedBlocks.ContainsKey(id)) cachedBlocks.Add(id, LoadFromSharePoint(id)) return cachedBlocks[id]; } public T LoadFromSharePoint(Guid id) { return new T(id) // Here is the problem. } } ``` The error message is: Cannot create an instance of type T because it does not have the new() constraint. I have to mention that I must pass that `id` parameter, and there is no other way to do so. Any ideas on how to solve this would be highly appreciated.

Original source

Related problems