1

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));
}
user1229895
  • 2,259
  • 8
  • 24
  • 26
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – usr May 30 '14 at 17:08

1 Answers1

2

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • I tried dropping the typeof, and I get a runtime error 'ArgumentNullException: Argument cannot be null' – user1229895 May 23 '12 at 04:44
  • 1
    Then I guess your `DiscoverType` method is returning a null-reference? Hard to say without looking at the stack-trace of the exception. – Ani May 23 '12 at 04:48
  • you're right I think it is null, i'm trying to get the Type by string...should Type.GetType(string) work? – user1229895 May 23 '12 at 04:54
  • Yes, but note this from MSDN: "The assembly-qualified name of the type to get. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace." – Ani May 23 '12 at 04:56
  • I should be passing it "System.Int32" or "System.String", not sure why its returning null – user1229895 May 23 '12 at 05:01