views:

61

answers:

3

I can't do this in C#:

    catch (Exception exception)
    {
        var wrappedException = new TException(exception);
    }

Getting error "cannot provide arguments when creating an instance of type parameter 'TException'. Just wanted to check with the community to see if there is any way to do something like this?

+1  A: 

This one should help you:

C# Lawyer: How to Create an Instance of a Generic Type with Parameters

Leniel Macaferi
That page encourages people to use the initialisation-instead-of-construction anti-pattern with no commentary on the down sides.
Jon Hanna
+2  A: 

The easiest (and best) method is to call Activator.CreateInstance yourself. This is what the C# compiler actually does, as the new() constraint just ensures that the specified type has a parameterless constructor; calling new TException() actually uses Activator.CreateInstance to instantiate the type.

Something like this would work:

throw (Exception)Activator.CreateInstance(typeof(TException), exception);
Adam Robinson
@Adam +1 Interesting, thanks for the background on what C# compiler is doing.
Paul Fryer
That totally worked!
Paul Fryer
+1  A: 

I find the easiest way to do this is to have the type in question take a factory lambda in addition to the generic parameter. This factory lambda is responsible for creating an instance of a generic parameter for certain parameters. For example

void TheMethod<TException>(Func<Exception,TException> factory) {
  ...
  catch (Exception ex) {
    var wrapped = factory(ex);
    ...
  }
}

Also I wrote a blog article on this problem recently that goes over various ways to solve this problem

JaredPar