Setting generic type at runtime

I have a class

public class A<T>
{
   public static string B(T obj)
   {
       return TransformThisObjectToAString(obj);
   }
}

The use of string above is purely exemplary. I can call the static function like this just fine on a known/specified type:

string s= A<KnownType>.B(objectOfKnownType);

How do I make this call, if I don't know T beforehand, rather I have a variable of type Type that holds the type. If I do this:

Type t= typeof(string);
string s= A<t>.B(someStringObject);

I get this compiler error:

Cannot implicitly convert type 't' to 'object'

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.


There's absolutely support for this in the framework and the CLR - just not gracefully in C#. You can accomplish what I think you want, though, with the help of a helper method:

public class A<T>
{
    public static string B(T obj)
    {
        return obj.ToString();
    }
}

public class MyClass
{
    public static void DoExample()
    {
        Console.WriteLine(ExecuteB("Hi"));
        Console.WriteLine(ExecuteB(DateTime.Now));
    }

    public static object ExecuteB(object arg)
    {
        Type arg_type = arg.GetType();
        Type class_type = typeof(MyClass);
        MethodInfo mi = class_type.GetMethod("ExecuteBGeneric", BindingFlags.Static | BindingFlags.Public);
        MethodInfo mi2 = mi.MakeGenericMethod(new Type[] { arg_type });
        return mi2.Invoke(null, new object[] { arg });
    }

    public static object ExecuteBGeneric<T>(T arg)
    {
        return A<T>.B(arg);
    }

You can't. Generic type identifiers have to be known at compile time.

edit

as of other posts, it appears to be possible by dynamicly generating the method and invoking it - which has dangers of course. See Thomas' and Dathan's posts for more inforation.


You can't. But you've asked the wrong question for the case provided. In this case (as in 99% of cases) all you actually need is a type constraint.

Try:

public class A<T> where T : object

or, if T is a known class, a subclass, or an interface then it would be better to use

public class A<T> where T : YourAbstractClass

Other type constraints also exist. More details: http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx

As a general note, when learning a new language, you often have to think broadly about what you want to achieve, not specifically finding what you want to do. This is much like real-world verbal languages. It's the difference between learning German by reading a dictionary and forcing the words into English syntax, or learning the syntax and picking up the words. Yes, a German speaker will understand someone who is speaking out of a dictionary, but the WTF per sentence count will be much higher.