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);
}
}
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:
where the
"aaa"
and"bbb"
is supplied at compile time, by inspection of the resolved method.