Practice mode C#

Given class A { public string M() => “A”; } class B : A { public new string M() => “B”; }, what does A x = new B(); Console.WriteLine(x.M()); print?

Correct answer B. A

Explanation

The new modifier hides the inherited member rather than overriding it. Calls are then resolved using the compile-time type of the variable. Because x is declared as A, the compiler binds to A.M and prints A, even though the object is a B. Only virtual methods with override give run-time dispatch. Method hiding is rarely what you want.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.