Reflection.Emit and generic methods

A

ayende

How do I use Reflection.Emit to produce code similar to this?

public void bar<T>()
{
}
public void foo<J>()
{
bar<J>();
}

More specifically, I don't know how to bind the method call using
Reflection.Emit.
Any suggestions?

The IL that is generated is:

..method public hidebysig instance void foo<J>() cil managed
{
// Code Size: 9 byte(s)
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: call instance void dempo::bar<!!0>()
L_0007: nop
L_0008: ret
}

But I don't see a way to get the !!0 from Reflection.Emit.
 
D

Daniel O'Connell [C# MVP]

How do I use Reflection.Emit to produce code similar to this?

public void bar<T>()
{
}
public void foo<J>()
{
bar<J>();
}

More specifically, I don't know how to bind the method call using
Reflection.Emit.
Any suggestions?

Look at the MakeGenericMethod method on MethodInfo. It should allow you to
bind to the method you want to call with the type parameters you want.
 
A

ayende

I looked at them, but that isn't the problem, I have the method info
for bar, I just don't know what to pass to make generic method?
 
D

Daniel O'Connell [C# MVP]

I looked at them, but that isn't the problem, I have the method info
for bar, I just don't know what to pass to make generic method?

Ahh, I see what you mean now. Try using the GetGenericArguments method, that
should return an array of types which will represent the generic arguments
for hte method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top