Reputation: 9537
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?
Upvotes: 3
Views: 177
Reputation: 755587
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
Upvotes: 1
Reputation: 185703
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);
Upvotes: 2