In C# Abstract class virtual and abstract method both? Why?

(Last Updated On: February 25, 2019)

Questions description:Can we have virtual method in an Abstract class in C#? If yes, what is the purpose of having virtual method and abstract method both in an abstract class if both allow derived classes to override and implement it. for example class below.

 

Answer: Yes, We can have virtual method in an Abstract class in C#.

This is true that both virtual and abstract method allow derived classes to override and implement it. But, difference is that an abstract method forces derived classes to implement it whereas virtual method is optional.

[Recommended: What C# feature will you use to keep common behaviors at one place and force clients to implement some others?]

If we don’t override an abstract class in derived classes compiler will flash an error. But, if we don’t override and implement virtual method it is ok.

Tips: In an interview, we should not stop here without an example. Try to pick some real one. If not, it will also be OK with some pseudo code. For example class A, virtual method xyz etc.

Complete Example:

 

 

Tips: If you have something more to say about it, it will be a bonus point.

Some time we design class on future requirement prediction. If we think that some derived classes may implement some behavior of an abstract class in future, we should make it virtual, so,  derived class can override and implement it. So, we don’t have to touch the base class again but extended class only.