Why is f (double) better than f (long, int = 0) for f (long)?

One of my colleagues finds this strange case. I am posting a simple example here:

using System;

namespace Test
{
    public class F
    {
        public void f(double d) { Console.WriteLine("public void F.f(double d)"); }
        public virtual void f(long l, int q = 0) { Console.WriteLine("public virtual void F.f(long l, int q = 0)"); }
    }

    public class FDerived : F
    {
        public override void f(long l, int q) { Console.WriteLine("public override FDerived.f(long l, int q)"); }
        public void g() { f(2L); }
    }

    public class G : FDerived
    {
        public void h1() { F fd = new FDerived(); fd.f(2L); }
        public void h2() { FDerived fd = new FDerived(); fd.f(2L); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new FDerived().g();
            new G().h1();
            new G().h2();
            Console.ReadLine();
        }
    }
}

Example Result:

public void F.f(double d)
public override FDerived.f(long l, int q)
public void F.f(double d)

I do not see how this might make sense.

Why is f (double) better than f (long, int = 0) for f (long)? And why does it depend on the type of 'fd' ?!

+4
source share
1 answer

I don't have C # Spec here, but optional parameter values ​​are not inherited by overridden methods.

Try to change FDerived

public override void f(long l, int q)

to

public override void f(long l, int q = 0)

and it will work as expected.

Note that this can be shown in a simple example:

public class F
{
    public virtual void f(long l, int q = 0) { Console.WriteLine("public virtual void F.f(long l, int q = 0)"); }
}

public class FDerived : F
{
    public override void f(long l, int q) { Console.WriteLine("public override FDerived.f(long l, int q)"); }
}

// Doesn't compile: No overload for method 'f' takes 1 arguments
new FDerived().f(5L);

Obviously this compiles:

new F().f(5L);

and even this one:

F obj = new FDerived();
obj.f(5L);

(this outputs public override FDerived.f(long l, int q))

+5
source

All Articles