Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling generic method with Type variable [duplicate]

Tags:

c#

generics

I have a generic method

Foo<T>

I have a Type variable bar

Is it possible to achieve something like Foo<bar>

Visual Studio is expecting a type or namespace at the bar.

like image 664
Daniel Elliott Avatar asked Oct 18 '10 09:10

Daniel Elliott


People also ask

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

How do you call a generic function in C#?

MethodInfo method = typeof(Foo). GetMethod("MyGenericMethod"); method = method. MakeGenericMethod(t); method. Invoke(this, new object[0]);

Can we have generic method in non generic class?

Yes, you can define a generic method in a non-generic class in Java.


2 Answers

Lets assume that Foo is declared in class Test such as

public class Test
{
   public void Foo<T>() { ... }

}

You need to first instantiate the method for type bar using MakeGenericMethod. And then invoke it using reflection.

var mi = typeof(Test).GetMethod("Foo");
var fooRef = mi.MakeGenericMethod(bar);
fooRef.Invoke(new Test(), null);
like image 154
VinayC Avatar answered Oct 10 '22 13:10

VinayC


If I understand your question correctly, you have, in essence, the following types defined:

public class Qaz
{
    public void Foo<T>(T item)
    {
        Console.WriteLine(typeof(T).Name);
    }
}

public class Bar { }

Now, given you have a variable bar defined as such:

var bar = typeof(Bar);

You then want to be able to call Foo<T>, replacing T with your instance variable bar.

Here's how:

// Get the generic method `Foo`
var fooMethod = typeof(Qaz).GetMethod("Foo");

// Make the non-generic method via the `MakeGenericMethod` reflection call.
// Yes - this is confusing Microsoft!!
var fooOfBarMethod = fooMethod.MakeGenericMethod(new[] { bar });

// Invoke the method just like a normal method.
fooOfBarMethod.Invoke(new Qaz(), new object[] { new Bar() });

Enjoy!

like image 54
Enigmativity Avatar answered Oct 10 '22 14:10

Enigmativity