C#.NET virtual members and overriding — which base-class modifier allows a derived instance to completely take over a member? In object-oriented C# design, a base class must opt-in to polymorphic override behavior. Choose the modifier the base class must use so that a derived class instance can provide its own implementation that replaces the base behavior at runtime.

Difficulty: Easy

Correct Answer: virtual

Explanation:


Introduction / Context:
In C#.NET, runtime polymorphism depends on whether the base member is declared in a way that permits overriding. If the base member does not allow overrides, a derived class cannot truly replace its behavior polymorphically.



Given Data / Assumptions:

  • We are discussing class inheritance in C#.
  • The goal is to allow a derived class to supply a replacing implementation.
  • The replacement must work via base references at runtime.


Concept / Approach:
The base class must mark a method or property as virtual (or abstract). A derived class then uses override to supply the new implementation. Using new merely hides a member at compile time but does not participate in dynamic dispatch through a base reference.



Step-by-Step Solution:

1) Base declares: virtual void M() { /* base */ }2) Derived declares: override void M() { /* derived */ }3) Calling M() through a Base reference bound to a Derived object invokes Derived.M().


Verification / Alternative check:
Test with Base b = new Derived(); b.M(); and observe the derived implementation executing.



Why Other Options Are Wrong:

  • new: hides, not overrides.
  • base: keyword to access base members, not a modifier to enable overriding.
  • overloads: relates to method overloading (same name, different signatures).
  • overrides: not a C# keyword (actual keyword is override, used in the derived class).


Common Pitfalls:
Confusing new with override leads to unexpected base behavior when using base-typed references.



Final Answer:
virtual

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion