Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Get type parameter at runtime to pass into a Generic method [duplicate]

Tags:

c#

types

generics

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 =)

like image 361
user1229895 Avatar asked Mar 12 '12 11:03

user1229895


2 Answers

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.

like image 131
Matthias Avatar answered Sep 20 '22 23:09

Matthias


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).

like image 20
Adrian Zanescu Avatar answered Sep 17 '22 23:09

Adrian Zanescu