Search code examples
c#type-parameter

Instantiate new object based on type parameter


I am trying to throw an exception based on the exception type parameter passed to the method.

Here is what I have so far but I don't want to specify each kind of exception:

public void ThrowException<T>(string message = "") where T : SystemException, new()
    {
        if (ConditionMet)
        {
            if(typeof(T) is NullReferenceException)
                throw new NullReferenceException(message);

            if (typeof(T) is FileNotFoundException)
                throw new FileNotFoundException(message);

            throw new SystemException(message);
        }
    }

Ideally I want to do something like new T(message) given I have a base type of SystemException I would have thought this was somehow possible.


Solution

  • I don't think that you can do this using gerics alone. You would need to use reflection. Something like:

    throw (T)Activator.CreateInstance(typeof(T),message);