Practice mode C#

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

Correct answer C. B

Explanation

Because M is virtual in A and overridden in B, the call is dispatched on the object's run-time type, not the variable's declared type. x refers to a B, so B's version runs and prints B. This is run-time polymorphism. If B had hidden the method with new instead of override, the call through an A reference would print A.

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.