Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# optional arguments in abstract method

Given:

interface IFoo
{
    void Print(string text = "abc");
}

class Bar : IFoo
{
    public void Print(string text = "def")
    {
        Console.WriteLine(text);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Bar b = new Bar();
        b.Print();

        IFoo f = b as IFoo;
        f.Print();
    }
}

The output is:

def
abc

Is just me or this is a little odd? Initially I was expecting "def" in both cases. However, if that would be the case then the optional argument abstract methods would be useless. But still seems like a good starting point for nasty bugs.

like image 253
Victor Hurdugaci Avatar asked Aug 10 '26 06:08

Victor Hurdugaci


1 Answers

Optional parameters are a compiler feature, and the compiler can only work on type information that's available at compile time. Therefore the values are taken from the type of the reference you're operating on, not the actual run-time type. In this simple test case it would be possible to find out the actual type of f via static analysis, but that only rarely works in real-life examples and therefore isn't implemented.

like image 78
Matti Virkkunen Avatar answered Aug 12 '26 00:08

Matti Virkkunen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!