75

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.

1
  • Can you show some code where you attempting to use it? It's definetely possible, so it's likely a syntax error. Commented Oct 18, 2010 at 9:21

2 Answers 2

103

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);
Sign up to request clarification or add additional context in comments.

2 Comments

What if class Test is static ? How to invoke fooRef ?
@Riomare, sorry for delayed response!. The first parameter to Invoke method is the instance on which method needs to be called on. For static methods, there will be no instance and hence null to passed e.g. fooRef.Invoke(null, null)
66

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!

5 Comments

+1 ... just a little later than accepted answer but wonderfully put!
@Daniel Elliot - Yes, I know - 41 seconds later. I was hoping that my slightly more detailed answer would prevail, but alas. ;-)
my code get work, best answer in detail.... Thanks
doesn't work. first line returns null
@AndrewGray - I test everything before posting.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.