Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to provide constructor parameters to generic instances?

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?

like image 802
Paul Fryer Avatar asked Feb 03 '26 14:02

Paul Fryer


2 Answers

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);
like image 140
Adam Robinson Avatar answered Feb 05 '26 02:02

Adam Robinson


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

  • http://blogs.msdn.com/b/jaredpar/archive/2010/06/04/using-lambdas-to-create-generic-factories.aspx
like image 26
JaredPar Avatar answered Feb 05 '26 04:02

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!