Note that there are some explanatory texts on larger screens.

plurals
  1. POCompiler Ambiguous invocation error - anonymous method and method group with Func<> or Action
    primarykey
    data
    text
    <p>I have a scenario where I want to use method group syntax rather than anonymous methods (or lambda syntax) for calling a function.</p> <p>The function has two overloads, one that takes an <code>Action</code>, the other takes a <code>Func&lt;string&gt;</code>.</p> <p>I can happily call the two overloads using anonymous methods (or lambda syntax), but get a compiler error of <em>Ambiguous invocation</em> if I use method group syntax. I can workaround by explicit casting to <code>Action</code> or <code>Func&lt;string&gt;</code>, but don't think this should be necessary.</p> <p>Can anyone explain why the explicit casts should be required.</p> <p>Code sample below.</p> <pre><code>class Program { static void Main(string[] args) { ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods(); ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods(); // These both compile (lambda syntax) classWithDelegateMethods.Method(() =&gt; classWithSimpleMethods.GetString()); classWithDelegateMethods.Method(() =&gt; classWithSimpleMethods.DoNothing()); // These also compile (method group with explicit cast) classWithDelegateMethods.Method((Func&lt;string&gt;)classWithSimpleMethods.GetString); classWithDelegateMethods.Method((Action)classWithSimpleMethods.DoNothing); // These both error with "Ambiguous invocation" (method group) classWithDelegateMethods.Method(classWithSimpleMethods.GetString); classWithDelegateMethods.Method(classWithSimpleMethods.DoNothing); } } class ClassWithDelegateMethods { public void Method(Func&lt;string&gt; func) { /* do something */ } public void Method(Action action) { /* do something */ } } class ClassWithSimpleMethods { public string GetString() { return ""; } public void DoNothing() { } } </code></pre>
    singulars
    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.
 

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