Here’s a simple code, where I try to implement some sort of polymorphysm.
You can see overloaded Invoker function, accepting Func<T,R> and Action<T> as an argument.
Compiler says it couldn’t be compiled because of ambiguity if Invoker methods:
class Program
{
static void Invoker(Action<XDocument> parser)
{
}
static void Invoker(Func<XDocument,string> parser)
{
}
static void Main(string[] args)
{
Invoker(Action);
Invoker(Function);
}
static void Action(XDocument x)
{
}
static string Function(XDocument x)
{
return "";
}
}
I get 3(!) errors, and none of it i can explain. Here they are:
Error 1 The call is ambiguous between the following methods or properties: ‘ConsoleApplication3.Program.Invoker(System.Action)’ and ‘ConsoleApplication3.Program.Invoker(System.Func)’ c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 21 4 ConsoleApplication3
Error 2 The call is ambiguous between the following methods or properties: ‘ConsoleApplication3.Program.Invoker(System.Action)’ and ‘ConsoleApplication3.Program.Invoker(System.Func)’ c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 4 ConsoleApplication3
Error 3 ‘string ConsoleApplication3.Program.Function(System.Xml.Linq.XDocument)’ has the wrong return type c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 12 ConsoleApplication3
Any ideas?
Both
and
have same method signature.
Return value is not part of method signature. So, just having a different return type won’t work. They must have different number of parameters or parameter types must be different.
Since, compiler cannot figure out which one (method that takes
Actionor method that takesFunc) to use, you have to explicitly specify it:to resolve ambiguity.