JeffreyZ. JeffreyZ. - 4 months ago 41
C# Question

Virtual methods without body

I was looking at some code in an abstract class:

public virtual void CountX(){}

public virtual void DoCalculation() { ...code}

Why should I declare an empty virtual method in an abstract class if it is not mandatory to override it in derived types?


As @Adam told you, there are many cases in which it makes sense. When you create an abstract class, it's because you want to create a common interface for all classes deriving from that one; however, at that level of inheritance you won't have enough information to be able to create working code for that method.

For example, if you create the class Figure, with the getArea() method, you won't be able to write code that is going to correctly calculate the area for all figures. You'll have to wait to write the code for Rectangle, or Circle (both deriving from Figure), in order to be able to write working code for them.