Reputation: 7223
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
Reputation: 54178
You can use the variadic overload Activator.CreateInstance Method (Type, Object[]) and it will use the best matching constructor.
Upvotes: 2
Reputation: 86848
You could just call object result = Activator.CreateInstance(typeof(T), e);
Upvotes: 1
Reputation: 169488
Yes, just supply the constructor arguments after the Type
object, like so:
object result = Activator.CreateInstance(typeof(T), arg1, arg2, ...);
Upvotes: 7