When new-able use new T(), otherwise use default(T)
You just need to check whether the type has a parameterless constructor. You do it by callingType.GetConstructor
method with empty types as parameter.
var constructorInfo = typeof(T).GetConstructor(Type.EmptyTypes);
if(constructorInfo != null)
{
//here you go
object instance = constructorInfo.Invoke(null);
}
If I remember correctly, Activator.CreateInstance<T>
will return an object constructed with the parameterless constructor if T
is a class or a default(T)
if T
is a struct.
You can use the technique in Sriram's answer to first make sure a parameterless constructor exists for T
.