Question

Trying to create a delegate to access an array, I get an ArgumentException saying that the method could not be bound.

Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

The minimum amount of code to reproduce this is the following:

var method = typeof(string[,]).GetMethod("Get");
var func = Delegate.CreateDelegate(typeof(Func<int, int, string>), new string[4,5], method);

Although the Get method is invisible by default, the first line does actually work and finds the correct method. As the signature matches, I assume the exception has something to do with the fact that the Get method is security-transparent, whereas Func<,,> is probably not. How to determine whether a delegate type is security-transparent and how to resolve this issue?

Was it helpful?

Solution

I think you found a CLR bug. There are two fundamentally different chunks of code that binds a delegate, BindToMethodInfo and BindToMethodName. They are quite painful to unravel due to the caching that occurs inside them, I'm guessing there's something wrong there and related to the fact that arrays are treated rather specially in .NET.

That this hasn't been noticed before is somewhat explainable, surely everybody that tried to do what you do is using the documented Array.GetValue() method. Like this:

   var method = typeof(string[,]).GetMethod("GetValue", 
                                     new Type[] { typeof(int), typeof(int) });
   var func = Delegate.CreateDelegate(typeof(Func<int, int, object>), 
                                     new string[4, 5], method);

Which works fine. You can post feedback at connect.microsoft.net to hear the experts' opinion, don't count on a quicky bug fix though.

OTHER TIPS

Um, I think you need to look at the signature of the method CreateDelegate.

var func = Delegate.CreateDelegate(typeof(Func<int, int, string>), new string[4, 5], method.Name);

see where I added method.Name? you are trying to send in a MethodInfo Class.

The actual signature of Get method has object return type.

Following is working:

var method = typeof(string[,]).GetMethod("Get");
var func = Delegate.CreateDelegate(typeof(Func<int, int, object>), new string[4,5], method);

Please check below link. It talks about the probable causes for Argument exceptions

http://msdn.microsoft.com/en-us/library/53cz7sc6(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top