Vadim
Vadim

Reputation: 17955

Why doesn't this trigger an "Ambiguous Reference Error"?

public class A
{
    public virtual string Go(string str) { return str; }
    }

public class B : A
{
    public override string Go(string str) {return base.Go(str);}
    public string Go(IList<string> list) {return "list";}
}

public static void Main(string[] args)
{
    var ob = new B();
    Console.WriteLine(ob.Go(null));
}

http://dotnetpad.net/ViewPaste/s6VZDImprk2_CqulFcDJ1A

If I run this program I get "list" sent out to the output. Why doesn't this trigger an ambiguous reference error in the compiler?

Upvotes: 12

Views: 267

Answers (1)

Diego Mijelshon
Diego Mijelshon

Reputation: 52735

Since the overload taking a string is not defined in B (only overriden), it has lower precedence than the one taking an IList<string>.

Therefore, the second overload wins and there's no ambiguity.

This is explained in detail in http://csharpindepth.com/Articles/General/Overloading.aspx

Upvotes: 15

Related Questions