Overriding default parameters in C# [duplicate]
Asked Answered
N

1

6

Really simple to replicate, the output is bizarre;

Expected output is "bbb bbb" Actual output is "aaa bbb"

Has anyone got any MSDN explanation of this behaviour? I couldn't find any.

((a)new b()).test();
new b().test();


public class a
{
    public virtual void test(string bob = "aaa ")
    {
        throw new NotImplementedException();
    }
}

public class b : a
{
    public override void test(string bob = "bbb ")
    {
        HttpContext.Current.Response.Write(bob);
    }
}
Niels answered 17/12, 2013 at 12:20 Comment(8)
Does ((a)(new b())).test() give the results you want?Sankaran
Expected output according to who?Externalize
I believe that it is invalid to change the default value of an optional parameter while overriding a method. Doesn't that change the method signature ?Jesse
Only if you dont understand the virtual and override keywords!Externalize
@Frederik: Shouldn't this throw a compiler warning if it is invalid?Clobber
@Clobber and if it was invalid, I suspect it wouldAlmsgiver
Indeed, the compiler should complain when it is invalid. It doesn't, but Resharper does ...Jesse
@Frederik It's not invalid, it's just potentially unwise.Oslo
A
12

Why do you expect "bbb bbb"?

Since you are casting the instance to a, the only information to the compiler on the first call is the version with "aaa", so that value is what is used.

In the second version without the cast, the compiler can see the "bbb", so that value is what is used.

Polymorphism impacts which method is invoked - but it doesn't impact the parameters passed. Essentially, the default values are supplied by the compiler (at the call-site), so your code is actually equivalent to:

((a)new b()).test("aaa");
new b().test("bbb");

where the "aaa" and "bbb" is supplied at compile time, by inspection of the resolved method.

Almsgiver answered 17/12, 2013 at 12:26 Comment(2)
So, to re-emphasize, default values are implemented at compile time, not runtime?Dupuis
@BolucPapuccuoglu yes; I already added in a bit more to highlight thatAlmsgiver

© 2022 - 2024 — McMap. All rights reserved.