19

The generic Method is...

    public void PrintGeneric2<T>(T test) where T : ITest
    {
        Console.WriteLine("Generic : " + test.myvar);
    }

I'm calling this from Main()...

    Type t = test2.GetType();       
    PrintGeneric2<t>(test2);

I get error "CS0246: the type or namespace name 't' could not be found" and "CS1502: best overloaded method match DoSomethingClass.PrintGeneric2< t >(T) has invalid arguments"

this is related to my previous question here: C# : Passing a Generic Object

I've read that the generic type can't be determined at runtime, without the use of reflection or methodinfo, but I'm not very clear on how to do so in this instance.

Thanks if you can enlighten me =)

Community
  • 1
  • 1
user1229895
  • 2,259
  • 8
  • 24
  • 26

3 Answers3

32

If you really want to invoke a generic method using a type parameter not known at compile-time, you can write something like:

typeof(YourType)
    .GetMethod("PrintGeneric2")
    .MakeGenericMethod(t)
    .Invoke(instance, new object[] { test2 } );

However, as stated by other responses, Generics might not be the best solution in your case.

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Matthias
  • 12,053
  • 4
  • 49
  • 91
  • This is a very good example of how to invoke a generic method when what you have is a runtime type, but the OP isn't actually trying to do this in his example. @Moo-Juice's answer correctly solves the OP's question. Still, +1 because I've come upon this answer multiple times when I needed it for this "runtime type as a generic parameter" scenario. ;) – JMD Feb 21 '17 at 01:11
8

Generics offer Compile Time parametric polymorphism. You are trying to use them with a type specified only at Runtime. Short answer : it won't work and it has no reason to (except with reflection but that is a different beast altogether).

Adrian Zanescu
  • 7,907
  • 6
  • 35
  • 53
2

Just call:

PrintGeneric2(test2);

The compiler will infer <t> from what you pass.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • 1
    your suggestion would force the compiler to infer T as System.Type. I don't think that will correctly reflect the OP intention of passing a runtime evaluated type – Adrian Zanescu Mar 12 '12 at 11:26
  • @AZ, no, it wouldn't. Ignore the `Type t = test2.GetType()` part completely, it's not needed here. `test2` implements `ITest` (see his previous question). Passing `test2` as-is, is enough here. – Moo-Juice Mar 12 '12 at 11:28
  • Fair enough. Did not check the other question so I was lacking the context of test2. I still stand by my assumption that the OP wants to resolve T dynamically at runtime somehow and that is not what generics are for – Adrian Zanescu Mar 12 '12 at 11:32
  • 2
    @AZ, I think he *thinks* he needs to resolve it dynamically when, in fact, he doesn't need to. :) – Moo-Juice Mar 12 '12 at 11:33