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 =)
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With