A virtual property in C# is a class property declared with theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
virtual modifier, indicating that its get, set, or init accessors can be overridden by derived classes. It establishes a default implementation in the base class while permitting subclasses to modify or entirely replace that behavior using the override modifier, thereby enabling runtime polymorphism.
Technical Characteristics
- Default Implementation: Unlike
abstractproperties, avirtualproperty must provide a complete implementation in the base class. This can be an auto-implemented property or a property with explicit backing fields. - Optional Overriding: Derived classes are not forced to override a virtual property. If omitted, the derived class inherits the base class’s accessors.
- Signature Parity and Covariance: Generally, the overriding property must exactly match the type, name, and access modifiers of the base virtual property. However, since C# 9, C# supports covariant return types for read-only (get-only) properties. This allows an overriding get-only property to return a more derived type than the base virtual property.
- Accessor Constraints: A derived class can only override the accessors defined in the base class. If the virtual property is read-only, the overriding property cannot add a
setorinitaccessor. - Init Accessor Enforcement: If a base virtual property utilizes an
initaccessor (introduced in C# 9) instead of asetaccessor, the overriding property must strictly respect this semantic. The derived class must also useinitand cannot change the inheritedinitaccessor into asetaccessor. - Base Invocation: Overriding accessors can invoke the parent class’s implementation using the
basekeyword, allowing developers to extend rather than completely replace the original logic. - Sealing: An overridden virtual property can be marked with the
sealedmodifier in a derived class to prevent further overriding in subsequent derived classes.
Syntax Visualization
Access Modifier Asymmetry
If a virtual property defines different access modifiers for its accessors (e.g., apublic get and a protected set), the overriding property must maintain that exact asymmetry explicitly.
Master C# with Deep Grasping Methodology!Learn More





