Note that there are some explanatory texts on larger screens.

plurals
  1. POOpen instance delegates to value types
    primarykey
    data
    text
    <p>Delegate.CreateDelegate fails when I try to create open instance delegates to value type methods that implement interfaces. Because the instance method is on a value type, the first argument must be a ref, so let's define a general delegate type for this:</p> <pre><code>delegate T2 VF&lt;T0, T1, T2&gt;(ref T0 arg0, T1 arg1); </code></pre> <p>Now here's a program that succeeds in creating an open instance delegate to int.ToString(string), but fails to create an open instance delegate to int.Equals(int):</p> <pre><code>class Program { static void Main(string[] args) { var tos = typeof(int).GetMethod("ToString", new[] { typeof(string) }); var tosopen = Delegate.CreateDelegate( typeof(VF&lt;int, string, string&gt;), null, tos); // success! var eq = typeof(int).GetMethod("Equals", new[] { typeof(int) }); var eqopen = Delegate.CreateDelegate( typeof(VF&lt;int, int, bool&gt;), null, eq); // previous line fails with "Error binding to target method" } } </code></pre> <p>This seems to be due to the fact that int.Equals(int) implements <code>IEquatable&lt;int&gt;</code>. Note that the following <em>does</em> work:</p> <pre><code>var x = typeof(IEquatable&lt;int&gt;).GetMethod("Equals", new Type[] { typeof(int) }); var xopen = Delegate.CreateDelegate( typeof(Func&lt;IEquatable&lt;int&gt;, int, bool&gt;), null, x); xopen(1,1); // returns true </code></pre> <p>But this isn't exactly what I want, since this would seem to box any integers passed as the first argument. I also don't want to compare any <code>IEquatable&lt;int&gt;</code>, I want to specifically call the method to compare two ints.</p> <p>Any thoughts on what's wrong here?</p> <p>A Microsoft Connect bug was <a href="https://stackoverflow.com/a/4326917/144873">mentioned here</a> that seems directly related, but that link no longer works for me, and I can't find that bug by searching.</p> <p>Edit: note that the same problem occurs when trying to create open instance delegates to overridden methods, so it's not just interface methods.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload