g.foley
g.foley

Reputation: 2172

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.

Upvotes: 4

Views: 1007

Answers (3)

Stephan
Stephan

Reputation: 4247

As others stated, this can only be done with reflection. But you could drop the type parameter and pass the instantiated exception to the function:

public void ThrowException(Exception e)
{
    if (ConditionMet)
    {
        if(e is NullReferenceException || e is FileNotFoundException)
        {
            throw e;
        }

        throw new SystemException(e.Message);
    }
}

Usage:

// throws a NullReferenceException
ThrowException(new NullReferenceException("message"));
// throws a SystemException
ThrowException(new NotSupportedException("message"));

Upvotes: 1

flipchart
flipchart

Reputation: 6578

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);

Upvotes: 6

Peter PAD
Peter PAD

Reputation: 2310

You can use

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

More at http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

Upvotes: 0

Related Questions