tags:

views:

79

answers:

2

SO lets say in my class I have:

public delegate bool MyFunc(int param);

How can I then do this

someObj.PassMeADelegateToExamine(this.MyFunc); // not possible!?!

SO that I can examine the delegate and perhaps use reflection or something idk to find out it's return type and any params it might have?

Basically if I can transform it into an (uncallable) Action object that woul dbe grand

+2  A: 

The "prototype" is just a new Type definition - it's not an actual instance that you would use directly. In your case, MyFunc is the delegate Type, not an actual delegate.

You could do:

void PassMeADelegateTypeToExamine(Type type) { ... }

And then call it:

someObj.PassMeADelegateTypeToExamine(MyFunc);
Reed Copsey
IIRC, unless MyFunc is a Type, and not a delegate name (like the OP posted), this isn't going to compile. You'd need `typeof(MyFunc)`.
Ruben
A: 

A delegate declaration is a type declaration, just like struct and class. So you can use

typeof(MyFunc)

To find the delegate's return type and arguments, you must look at the delegate type's Invoke method:

MethodInfo invokeMethod = typeof(MyFunc).GetMethod("Invoke");
Type returnType = invokeMethod.ReturnType;
ParameterInfo[] parameterInfos = invokeMethod.GetParameters();

A delegate is pretty much a class with some conventional methods like Invoke. When you use a delegate instance like so

func(args)

This is translated internally to

func.Invoke(args)

Which is why there is no special DelegateInfo type in the reflection namespace: the Invoke method's MethodInfo tells you all you need.

Now, if you'd want to call a delegate instance dynamically, you can either use reflection and call Invoke on your MethodInfo or make sure your delegate variable is typed as Delegate, which gives you access to the DynamicInvoke method:

Delegate func = ...;
object result = func.DynamicInvoke(arg1, arg2);
Ruben
This is truly great stuff man, thanks so much I will accept your answer when it lets me.
Jeff Dahmer