What is Virtual Property in C#? Give an example.
Short answer
A virtual property is a property declared in a base class using the virtual keyword, which allows a derived class to override its behavior using the override keyword, giving subclasses the ability to provide their own custom implementation of the getter or setter while still…
Advertisement
AModel answer
A virtual property is a property declared in a base class using the virtual keyword, which allows a derived class to override its behavior using the override keyword, giving subclasses the ability to provide their own custom implementation of the getter or setter while still being accessible through the same property name.
public class Shape {
public virtual double Area {
get { return 0; }
}
}
public class Circle : Shape {
public double Radius { get; set; }
public override double Area {
get { return Math.PI * Radius * Radius; }
}
}Real-world example
A shape hierarchy defines a virtual Area property on a base Shape class, and each specific shape like Circle or Rectangle overrides it with its own correct area calculation formula, letting calling code treat every shape uniformly through the same Area property.
Likely follow-ups
- What happens if a derived class does not override a virtual property?
- What is the difference between a virtual property and an abstract property?
Related topics