Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this kind of abuse of generics not ambiguous/trigger an error in the compiler

I've been feeling my way around the C# compiler with it's limits of "inherited instantiated generic classes".

Anyway, This is my test case:

class Program
{
    static void Main(string[] args)
    {
        var x = new InClass();
        Console.WriteLine(x.Test(10)); //prints foo
        Console.ReadLine();
    }
}
class BaseClass<Foo, Bar>
{
    public virtual Foo Test(Bar b)
    {
        return default(Foo);
    }
    public virtual string Test(int b)
    {
        return "foo"; ;
    }
}
class InClass : BaseClass<string, int>
{
    /*public override string Test(int b)
    {
        return "bar";
    }*/
}

I would think that this declaration of InClass would throw a compiler error, as it makes Test ambiguous. It also makes the non-generic Test impossible to call within the InClass. Notice I have some code commented out in InClass as well. If I uncomment that code, I do get a compiler error.

Is there a mention of this behavior at all in the C# spec, or is this an unheard of edge case?

like image 937
Earlz Avatar asked Feb 19 '23 09:02

Earlz


1 Answers

I would think that this declaration of InClass would throw a compiler error, as it makes Test ambiguous.

Nope. The specification calls out this kind of thing explicitly in section 7.5.3.6:

While signatures as declared must be unique, it is possible that substitution of type arguments might result in identical signatures. In such cases, the tie-breaking rules of overload resolution above will pick the most specific member.

The following examples show overloads that are valid and invalid according to this rule.

(Examples follow, obviously.)

So the language designers have considered it, but presumably the alternatives would be worse. (It would be annoying to not be able to create a class such as InClass even when you didn't want to call Test, for example.)

like image 62
Jon Skeet Avatar answered Mar 09 '23 07:03

Jon Skeet