Let T be a generic type. I would like to do something like this:
T x = default(T);
if (T has standard constructor)
x = new T();
Of course, one could restrict T to types having such a constructor, but I do not want ot exclude value types.
How can you do that?
You’ll have to use reflection:
You can also use
Activator.CreateInstance<T>(), but that will throw an exception if the constructor doesn’t exist.