When new-able use new T(), otherwise use default(T)

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?

Answers


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.


You could something like checking for a default constructor and execute new T() if one is found. To do this you could use something like:

var constructor = typeof(T).GetConstructor(Type.EmptyTypes);
if(constructor != null)
{
    return (T)constructor.Invoke(null);
}
else
{
    return default(T);
}

Need Your Help

Python `if x is not None` or `if not x is None`?

python coding-style boolean-expression

I've always thought of the if not x is None version to be more clear, but Google's style guide and PEP-8 both use if x is not None. Is there any minor performance difference (I'm assuming not), and...

Checking if the string is empty

php string validation

I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it.