I am working on a C# generic function. When error, if the generic type can be new-able, return new T()
, otherwise return default(T)
.
The code like this:
private T Func<T>()
{
try
{
// try to do something...
}
catch (Exception exception)
{
if (T is new-able) // <---------- How to do this?
{
return new T();
}
else
{
return default(T);
}
}
}
I know it needs where T : new()
for those using new T()
. This question is, how to judge this on runtime?
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);
}