I have a very simple generic constructor method:
public T Instance<T, TT>(TT parms) where T : class
{
return (T)Activator.CreateInstance(typeof(T), new[] { parms });
}
When I call the method like:
Instance<MyClass, string>("SomeStringValue").Customers.Where(x => x.Id == Id).Select(p => blah..blah...blah;
I get a ‘System.MissingMethodException: Constructor on type ‘MyClass’ not found.
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture…’
I have tried adding bindingflags etc. but without any luck.
I am basically trying to instantiate an object with arguments.
I can without any problems explicitly declare the object:
var myObj = new MyClass("SomeStringValue");
But I need to make use of my generic constructor.
Can anyone clarify what I am missing?
EDIT
A complete program (simplified).
public abstract class A
{
public T Instance<T, TT>(TT parms) where T : class
{
return (T)Activator.CreateInstance(typeof(T), new[] { parms });
}
}
public class B
{
public B(string someValue)
{
var myValue = someValue;
}
}
public class C
{
public void DoStuff()
{
var x = Instance<B, string>("SomeStringValue");
}
}
Is what I am trying to do.
The
Activator<T>.CreateInstance()overload you’re trying to call expects a second argument of typeObject[]. The new array you are creating is aTT[]. IfTTwere constrained to a class type, then aTT[]might satisfy theObject[]parameter. An unconstrained genericTT[], however, cannot be used as anObject[]. Once the compiler determines that theTT[]cannot be passed as anObject[], it then (because of theparamsspecification on the second parameter of the overload), it checks whether the second parameter you’re passing qualifies as anObject. Because all arrays derive fromObject, it will. The compiler will thus create a single-element array of typeObjectwhich holds theTT[]that you were trying to pass in. Since there is no constructor that expects anObject[], the call will fail.If you want to prevent this problem, create a new
Object[]containing the appropriate parameters, instead of creating a newTT[]. That should solve your problem.