Ilya Smagin
Ilya Smagin

Reputation: 6152

C# Polymorphysm: overloading function, accepting delegates Action<T> and Func<T,R>?

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?

Upvotes: 3

Views: 847

Answers (3)

Dan
Dan

Reputation: 93

Slightly more elegant solution using linq:

 public static void Main(string[] args)
 {
     Invoker((xdocument)=>doSomething);      // calls action invoker
     Invoker((xdocument)=>{return doSomething;}); // calls function invoker
}

At the end of it... comes down to signatures.

Upvotes: 3

Rafal Spacjer
Rafal Spacjer

Reputation: 4918

You can invoke your methods like that:

public static void Main(string[] args)
 {
     Invoker(new Action<XDocument>(Action));
     Invoker(new Func<XDocument, string> (Function));
}

Simply, you have to tell compiler what method you want to invoke.

Upvotes: 4

decyclone
decyclone

Reputation: 30830

Both

static void Action(XDocument x)

and

static string Function(XDocument x)

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 Action or method that takes Func) to use, you have to explicitly specify it:

Invoker(new Action<XDocument>(Action));
Invoker(new Func<XDocument, String>(Function));

to resolve ambiguity.

Upvotes: 6

Related Questions