Call ambiguous between methods that return different types when the return type is explicit [duplicate]

StackOverflow https://stackoverflow.com/questions/13650925

  •  03-12-2021
  •  | 
  •  

Question

Possible Duplicate:
Question about ambiguous calls in C#

I have these two methods:

TypeA MyMethod(string s) {}
TypeB MyMethod(string s) {}

The following call gives me "ambiguity between methods" error:

TypeA ta = MyMethod("some string");

How does this happen when I'm asking for a TypeA object to return explicitly and not via var or otherwise?


TypeA and TypeB are separate classes, they don't have anything in common.

Was it helpful?

Solution

From the C# spec v4.0, section 1.6.6:

The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.

You have two methods with the same signature because they differ only in the return type. This is not allowed.

OTHER TIPS

You cannot overload return types , if you are calling the method in this way

TypeA ta = MyMethod("some string");

then it would obvious to the compiler to pick a method.But what happens if you call it in this way

MyMethod("some string");

you are not using the value returned by the method,then the compiler will not be able to pick an appropriate method to call, this why it is an ambiguous call

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top