Home >Backend Development >C++ >Why Does Method Group Syntax Cause Ambiguous Invocation Errors with Delegate Overloads?
Ambiguous calling errors caused by C# method group syntax and delegate overloading
Scenario:
Suppose you want to call a function that has two overloads: one that accepts an Action delegate and another that accepts a Func
Question:
When you try to call these overloads using method group syntax, you will encounter a compiler ambiguous call error.
Explanation:
The reason for this ambiguity lies in the implicit conversion rules for method groups and delegate types. According to the C# specification, method groups can be implicitly converted to compatible delegate types. However, "compatibility" in this context refers to the compatibility of methods and delegate types, not the compatibility of method groups and delegate types.
In the given example, the method group classWithSimpleMethods.GetString
is a valid candidate for both delegate overloads: classWithDelegateMethods.Method(Action)
and classWithDelegateMethods.Method(Func<string>)
. Since there are no clear type rules to determine which conversion is better, the compiler generates an ambiguous call error.
Solution:
To resolve this ambiguity, you can provide an explicit cast to the corresponding delegate type, as follows:
<code class="language-csharp">classWithDelegateMethods.Method((Action)classWithSimpleMethods.DoNothing); classWithDelegateMethods.Method((Func<string>)classWithSimpleMethods.GetString);</code>
C# 7.3 Update:
Starting in C# 7.3, you no longer get ambiguous call errors when using method group syntax. Thanks to improved ordering of overload candidates, the compiler now correctly infers the expected delegate type based on context.
The above is the detailed content of Why Does Method Group Syntax Cause Ambiguous Invocation Errors with Delegate Overloads?. For more information, please follow other related articles on the PHP Chinese website!