Reputation: 2319
I'm trying to call a generic method and need to pass it a Type dynamically. But get a compile error, 'CS0246: The type or namespace name `t' could not be found. Are you missing a using directive or an assembly reference'. Please tell me what I'm overlooking, thank you.
...in the main...
Type t = DiscoverType(field); // returns Type given FieldInfo via Type.GetType(string)
MethodInfo method = typeof(testClass).GetMethod("MyGenericMethod", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo generic = method.MakeGenericMethod(typeof(t));
object[] args = {field};
generic.Invoke(this, args);
the generic method...
private void MyGenericMethod<T>(FieldInfo field)
{
field.SetValue(obj, new List<T>(objList));
}
Upvotes: 1
Views: 1258
Reputation: 113452
Hard to know what exactly you are trying to do, but you can fix your compiler error like this:
MethodInfo generic = method.MakeGenericMethod(t);
You use the typeof
operator to go from a type-name to a System.Type
instance. In your case, you already have the System.Type
instance you need so typeof
isn't useful here.
Upvotes: 2