dexter
dexter

Reputation: 7223

How can I call the constructor?

I dynamically create instances of my objects in the custom linq provider I am building using this call:

 object result = Activator.CreateInstance(typeof(T));

My T type implements an abstract class that has a constructor to take an instance of another object (T is essentially a wrapper). My question is - is there a way I can explicitly call the non-default constructor so I can get rid of this:

 MyEntity entity = result as MyEntity;
 if(entity != null)
    entity.UnderlyingEntity = e; //where e is what I am wrapping 

Upvotes: 1

Views: 170

Answers (3)

Steve Townsend
Steve Townsend

Reputation: 54178

You can use the variadic overload Activator.CreateInstance Method (Type, Object[]) and it will use the best matching constructor.

Upvotes: 2

Gabe
Gabe

Reputation: 86848

You could just call object result = Activator.CreateInstance(typeof(T), e);

Upvotes: 1

cdhowie
cdhowie

Reputation: 169488

Yes, just supply the constructor arguments after the Type object, like so:

object result = Activator.CreateInstance(typeof(T), arg1, arg2, ...);

Upvotes: 7

Related Questions