Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check compatibility of a method with a given Delegate?

In C# code, how do I check if a given method can be represented by a particular delegate type?

I first tried something, based on my Type knowledge, along the lines of:

// The delegate to test against.
void TargetDelegate(string msg);

// and...
var methodInfo = Type.GetMethod(..);  // obtain the MethodInfo instance. 
// try to test it 
typeof(TargetDelegate).IsAssignableFrom(methodInfo.GetType());

but that deals with only Types and not methods - it will always be false.

My inclination is to believe the answer lies in the Delegate Type, but I'm just wandering around the FCL at this point. Any help would be appreciated.

like image 569
John K Avatar asked Mar 31 '11 18:03

John K


1 Answers

I'd try:

Delegate.CreateDelegate(typeof(TargetDelegate), methodInfo, false) != null

This will try to create the delegate and return null on failure. If it return null, it should mean that the delegate was not able to be created. If it returns anything else, the delegate must be OK.

like image 72
Gabe Avatar answered Nov 12 '22 02:11

Gabe