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?
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With