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?