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

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.

abstract class Car
{
    public virtual void speed() {Console.WriteLine("120 kmph");}    
    public abstract void mileage();   
}

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:

abstract class Car
{
    public virtual void speed()
    {
        Console.WriteLine("120 kmph");
    }
    //Force derived classes to implement
    public abstract void mileage();   
}
class Zen : Car
{
    // This function implementation is optional and 
    //depend upon need if a derived class want to 
    //implement it or else base class implementaion will be used.
    //public override void speed()
    //{
    //    Console.WriteLine("Zen Speed:70 kmph");
    //}

    //This class must implement this function.
    public override void mileage()
    {
        Console.WriteLine("Zen mileage:1200cc");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car c = new Zen();
        c.speed();
        c.mileage();        
    }   
}

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.

Related Posts