In a C# class, which members can be declared as virtual (eligible for overriding)?

Difficulty: Easy

Correct Answer: Methods, properties, and events

Explanation:


Introduction / Context:
Virtual members enable derived classes to provide specialized behavior. Misunderstanding which members can be marked virtual leads to incorrect designs and compiler errors.



Given Data / Assumptions:

  • C# allows virtual on instance members that support overriding.
  • Fields (including static fields) cannot be virtual.


Concept / Approach:
Virtual is permitted on methods, properties, and events. Fields store data and do not participate in polymorphic dispatch, therefore they cannot be virtual. Static members also do not participate in instance polymorphism.



Step-by-Step Solution:

Evaluate methods → can be virtual.Evaluate properties → can be virtual (their accessors can be overridden).Evaluate events → can be virtual.Evaluate fields (instance/static) → cannot be virtual.


Verification / Alternative check:
Try compiling 'public virtual int x;' or 'public virtual static int y;'; both will fail. 'public virtual int P { get; set; }' compiles and can be overridden.



Why Other Options Are Wrong:
Any option listing fields or static fields as virtual is invalid in C#.



Common Pitfalls:
Assuming virtual applies to data the same way as to behavior; forgetting that polymorphism targets methods (including property/event accessors).



Final Answer:
Methods, properties, and events

More Questions from Polymorphism

Discussion & Comments

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