Setting generic type at runtime

You can’t do this directly, but you can use reflection to provide a type parameter of a class at run-time. I haven’t tested this, but something like this should work:

// We want to do something like this:
//    object o = "Hello"
//    Type t = o.GetType(); 
//
// This is pseudo-code only:
//    string s = A<t>.B(o); 

string InvokeA(object o) {
  // Specify the type parameter of the A<> type
  Type genericType = typeof(A<>).MakeGenericType(new Type[] { o.GetType() });
  // Get the 'B' method and invoke it:
  object res = genericType.GetMethod("B").Invoke(new object[] { o });
  // Convert the result to string & return it
  return (string)res;
}

Of course, the question is if this is really what you need – If you don’t know anything about the object given as an argument, you could as well write the whole code just using object. However, I can imagine some scenarios where this would be useful, so I guess you can try using this.

Leave a Comment