Overriding default options in C #

In fact, just for replication, the conclusion is bizarre;

Expected Result: "bbb bbb" Actual Output - "aaa bbb"

Has anyone got an MSDN explanation of this behavior? I could not find.

((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); } } 
+6
source share
1 answer

Why do you expect "bbb bbb"?

Since you run the instance before a , the only information for the compiler on the first call is the version with "aaa" , so this value is used.

In the second version, without translation, the compiler can see "bbb" , so this value is used.

Polymorphism affects the method that is called - but it does not affect the parameters passed. Essentially, the default values ​​are supplied by the compiler (on the call site), so your code is actually equivalent:

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

where "aaa" and "bbb" provided at compile time , checking the allowed method.

+12
source

All Articles