Pages

24.5.11

Abstract vs. Virtual in C#

There are several keywords that can be used for inheritance in object-oriented programming languages. In C#, you can specify a method as abstract or virtual.

In the concrete class, you must override any method marked as abstract. You can override
virtual
methods. In addition, you can provide new implementation for normal methods that are neither
abstract nor virtual. In this case, it's recommended to use the new keyword.

What's the difference between abstract and virtual methods? How can I use them to serve my design? In this article, I'm trying to answer these questions.

Of course the abstract method doesn't have implementation. It just defines the method. But is there any other differences? Let's take an example of two classes. An abstract class and another one that inherits from it.
Class diagram of an abstract class and a concrete one


// the abstract class
public abstract class BaseClass
{
    public abstract string GetAbstractValue();

    public virtual string GetVirtualValue()
    {
        return "Base GetVirtualValue";
    }

    public string GetValue()
    {
        return "Base GetValue";
    }
}


// the concrete class
public class ConcreteClass : BaseClass
{
    public override string GetAbstractValue()
    {
        return "Concrete GetAbstractValue";
    }

    public override string GetVirtualValue()
    {
        return "Concrete GetVirtualValue";
    }

    public string GetValue()
    {
        return "Concrete GetValue";
    }
}

Let's make a console application that uses the above classes. We want to make 2 instances of the concrete class. The first one should be of type
BaseClass and the other one of type ConcreteClass.

The client code should look like this:

class Program
{
    static void Main(string[] args)
    {
        BaseClass instance1 = new ConcreteClass();
            
        Console.WriteLine(instance1.GetAbstractValue());
        Console.WriteLine(instance1.GetVirtualValue());
        Console.WriteLine(instance1.GetValue());


        ConcreteClass instance2 = new ConcreteClass();

        Console.WriteLine(instance2.GetAbstractValue());
        Console.WriteLine(instance2.GetVirtualValue());
        Console.WriteLine(instance2.GetValue());


        Console.Read();
    }
}

Let's now see and compare the results.

The results of running the application

What do you conclude from the results?

Let's make another experiment before conclusion. Let's remove the following 2 methods from the
ConcreteClass

  • GetVirtualValue
  • GetValue

Try to run the application and notice the results.

The results after removing the 2 methods

From the previous results we can conclude the following:


Abstract Virtual No Keyword
Can have implementation?  No Yes Yes
Can override? Must Can but not a must You can declare a new method with the same name
Which keyword to use to provide new implementation in the concrete class? override override No keyword needed
If an object is created of the base class type, which method will be executed? Concrete implementation The parent implementation will be called only if no implementation is provided in the concrete class Parent implementation
If an object is created of the concrete class type, which method will be executed? Concrete implementation Concrete implementation The parent implementation will be called only if no implementation is provided in the concrete class

34 comments:

  1. Just made my day. Thank you !!

    ReplyDelete
  2. You're welcome. I'm happy that it helped you.

    ReplyDelete
  3. In the Concrete Class, While defining public string GetValue(), i think 'New' keyword should be used.

    ReplyDelete
  4. Yes, you're correct. New keyword should better be used. However, the code will still compile without it but you'll get warning according to your warning settings.

    ReplyDelete
  5. Very useful..!! Thanks!

    ReplyDelete
  6. MAVUNDLA K
    This is working and is usefull, thankx I understand it.

    ReplyDelete
  7. This is the very good way to get your answered

    ReplyDelete
  8. you should write a book. very well described and easy to follow.

    ReplyDelete
  9. Thanks for the complement jgoeke :)

    ReplyDelete
  10. If an object is created of the concrete class type, which method will be executed? For Virtual I thought it will be Concrete implementation if implementation is provided in the concrete class
    otherwise the parent implementation will be called ?

    ReplyDelete
  11. Excellent explanation

    ReplyDelete
  12. Really i got good idea about Virtual Class...

    ReplyDelete
  13. nice artical, I have a little confusion in Abstract Class and Interface, Both support inheritance feature and if any child class inherit Abstract or Interface then they must be implement Abstract method as well as interface method so my confusion is that why we use abstract class in comparison of interface.

    2. Can i use access modifier in abstract class?

    Thank you ...

    ReplyDelete
  14. In interfaces, you cannot provide default method implementation, whereas it's possible in abstract classes

    ReplyDelete
  15. Good Post
    Tehseen Ahmed
    ISlamabad, Pakistan

    ReplyDelete
  16. new keyword is required in concrete class to hide BaseClass GetValue()

    // the concrete class
    public class ConcreteClass : BaseClass
    {
    public override string GetAbstractValue()
    {
    return "Concrete GetAbstractValue";
    }

    public override string GetVirtualValue()
    {
    return "Concrete GetVirtualValue";
    }

    new public string GetValue()
    {
    return "Concrete GetValue";
    }
    }

    ReplyDelete
  17. Very clear ~ Thanks a lot

    ReplyDelete
  18. Nice explanation

    ReplyDelete
  19. Beautiful article..thanks for sharing!

    ReplyDelete

  20. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete
  21. The difference between the abstract and virtual in c# are explained well my sincere thanks for sharing this post
    Dot Net Training in Chennai

    ReplyDelete
  22. We give that answer difference between abstract vs virtual information I read and learning for virtual abstract menuval information.Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep updating your blog.If want to learn about Java Training to learn belongs to click for upcoming site link,Java Training in Chennai | Java Training Institute in Chennai

    ReplyDelete
  23. I love the information you provide here and can’t wait to take a look when I get home. I’m surprised at how fast your blog loaded on my cell phone.
    safety course in chennai

    ReplyDelete
  24. Best explanation ever, previously I was looking for a info about this technology and now I am Clear. Thanks.

    selenium testing training in chennai
    Best selenium training in chennai
    selenium Classes in chennai
    selenium course

    ReplyDelete
  25. The young boys ended up stimulated to read through them and now have unquestionably been having fun with these things.
    safety course in chennai

    ReplyDelete
  26. Thanks for sharing this great article. It made me understand few things about this concept which I never knew before. Keep posting such great articles so that I gain from it. Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai

    ReplyDelete
  27. I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.
    MCSE Training in chennai | mcse training class chennai

    ReplyDelete

Promotional Code for Udemy ServiceNow CIS - HR Practice Tests

If you're planning to become ServiceNow Certified Implementation Specialist - Human Resources (CIS-HR), you can prepare for the exam usi...