C# Abstract class Vs Interface | 10 differences between Abstract class and Interface with examples

In this article, We are going to discuss the “difference between Abstract class and Interface in C#” with simple examples.

This is one of the most frequently common questions asked in almost every C# dot net interview.

image result Interface Vs Abstract Class
interface vs abstract class c#

C# Abstract class Vs Interface

10 Difference between the abstract class and interface

In the following examples, let’s review our understanding of abstract classes and interfaces until C# 8.0 arrives.

The following is the list of 10 differences between the abstract class and the interface.

Abstract ClassInterface
1. In C#, An Abstract class can have public, private, or protected class members.Every method, properties or event inside an Interface must be public only by default.
2. An abstract class in C# can contain constructors.An interface in C# can’t contain a constructor
3. Multiple inheritance is not supported by an abstract class in C#.Interface support multiple inheritance in C#.
4. A class can be inherited by only one abstract class.A class can inherit by multiple interfaces.
5. An abstract class in C# can be fully implemented, partially implemented, or not implemented.An interface contains only the signatures of methods, properties, events, or indexers not the implementation.
6. Abstract class members such as methods or properties can be defined as abstract, virtual, static, or sealed.Interface members can’t be defined as abstract, virtual, static, or sealed.
7. Abstract class in C# contains both declaration and definition parts.An interface in C# contains only (signature) the declaration part.
8. An abstract class can contain fields and constants.An interface cannot have fields.
9. If multiple implementations of methods are of the same kind and use common behavior, then it’s better to use an abstract class. So that common implementation code does not need to be repeated in each of the descending or subclasses.If multiple unrelated classes only share method signatures and have different implementations of methods, then it is better to use Interface.
10. An abstract class can contain the main method in C#.An interface can’t contain the main method.
Difference between Abstract class and Interface in C# .NET

Abstract class: In C#, An abstract class is a way to achieve the abstraction, which is intended to hide the internal details and showing only the functionality. An Abstract class is not allowed to be instantiated directly instead it is typically used to define a base class in the class hierarchy. It provides the common code implementation to the derived classes.

When to use an Interface in C#?

Below is the list of reasons for using the interface.

Following are the Important reasons for using interfaces in C#:

    • You can achieve loose coupling by using the interface.
    • An interface can be used when you want the derived classes to fully implement all of the methods introduced in the base class.
    • Abstraction can be achieved via interfaces.
    • Interface Allows you to decouple a method’s definition from its inheritance hierarchy.
    • An interface can be used to achieve polymorphic behavior, a single method of an Interface can have multiple redefinitions into multiple classes of unrelated types. Here, every derived class is free to provide its own implementation.
    • Multiple inheritance is possible using interfaces in C#. however, a class cannot be inherited from multiple abstract classes.
    • Interfaces are best suited to achieve Dispose Pattern by defining an  IDisposable  interface.
    • An Interface doesn’t contain a constructor, due to which it helps to prevent extra roundtrip when creating an object of the derived class through the reference pointer of the interface.
    • An Interface can be great choice when we want to loop through a collection for example by using an  IEnumerable  interface.

When to use Abstract class Instead of Interface in C#?

This is one of the most asked questions that gets asked during C# dot net interviews. The majority of the developers are still not quite clear about the right answer.
Using the following points, I will try to explain these things.

    • The Abstract classes offer default functionality for the derived classes.
    • It is a great choice if you want to share a common code among several closely related classes. It acts as a base class and provides the common code implementation to the derived classes.
    • An abstract class can be used to achieve versioning of the components because by adding the new functionality to the base class all the derived classes will get updated automatically. An interface on the other hand can’t be modified once created and inherited by the classes. If we want to add a new method to the interface, we must create a new interface.
    • You can go with the abstract class if you wanted to provide the default implementation to all the subclasses.
    • The Abstract class allows code reusability.
    • You can use an abstract class if we don’t want to implement all of the methods in a derived class but only some of them in a parent class.

Example of an abstract class in C#

Let’s create a simple program of an abstract class.

using System;

namespace AbstractClassDemo
{
    // Abstract class

    public abstract class Bank
    {
        // Abstract method
        public abstract void CashWithdraw(double amount);

        //field
        protected double balance;
        // Concrete method
        public void Balance()
        {
            Console.WriteLine($" Total Balance: {this.balance}");
        }
    }

    // Derived class "HsbcBank" inheriting base "Bank" class
    public class HsbcBank : Bank
    {
        // Constructor
        public HsbcBank(double amount)
        {
            this.balance = amount;
        }

        // Implementing base class method
        public override void CashWithdraw(double amount)
        {
            if (amount > this.balance)
            {
                Console.WriteLine(" Insufficient funds in bank account");
                return;
            }
            Console.WriteLine($" Withdrawing Cash ${amount} from HSBC Bank.");
            Console.WriteLine($" Remaining Balance : {this.balance - amount}");
        }
    }

    // Derived class "CityBank" inheriting base "Bank" class
    public class CityBank : Bank
    {
        // Constructor
        public CityBank(double amount)
        {
            this.balance = amount;
        }
        // Implementing base class method
        public override void CashWithdraw(double amount)
        {
            if (amount > this.balance)
            {
                Console.WriteLine(" Insufficient funds in bank account");
                return;
            }

            Console.WriteLine($" Withdrawing Cash ${amount} From City Bank.");
            Console.WriteLine($" Remaining Balance : {this.balance - amount}");
        }
    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine("***** Abstract class example in C# *****");
            
            Bank bank = new HsbcBank(5000);
            bank.Balance();
            bank.CashWithdraw(300);

            Console.WriteLine();

            bank = new CityBank(10000);
            bank.Balance();
            bank.CashWithdraw(500);
           

            Console.ReadLine();
        }
    }   
}

Abstract class example
The output of the above abstract class program.

What’s new about interface in C# 8.0

 C# 8.0  changed a lot of things about the interface and most of the folks are still not aware of these new changes.

So let’s try to explore the new features of Interface introduced in C# 8. We will try to understand how we can use these features in our projects with simple examples.

Default Interface Methods Introduced In C# 8.0

The Default interface method which is also known as the virtual extension method is a new feature introduced in C# 8.0

It allows an Interface to add a method with implementation without breaking the existing functionality. Before C# 8 an interface was allowed to contains only (signature) the declaration part of methods, properties, events, or indexers, but now after C# 8.0 interface can contain both the declaration and the implementation.

Example of default interface method

The following is the simple program to illustrate the concept of the default interface method in C# 8

using System;

namespace DefaultInterfaceMethodDemo
{
    // Default Interface Method In C# 8.0

    interface IDefaultInterface
    {
        // This "ShowMessage" method is having only the declaration part.    
        void ShowMessage(string text);

        // Default interface method with both declaration and definition (Implementation).
        //Now Interface members can be public, private, or protected
        public void DefaultInterfaceMethod()
        {
            Console.WriteLine("Default method of interface!");
        }
    }

    // A class that implements
    // the "IDefaultInterface" interface.
    class MyClass : IDefaultInterface
    {
        // Providing implementation
        // part of the "ShowMessage" method
        void IDefaultInterface.ShowMessage(string text)
        {
            Console.WriteLine(text);
        }
    }

    class Program
    {
        static void Main()
        {
            IDefaultInterface myClass = new MyClass();

           // Calling default interface method
            myClass.DefaultInterfaceMethod();
            myClass.ShowMessage("Hello World!");

            Console.ReadLine();
        }
    }   
}
// Output
// Default method of interface!
// Hello World!
Default Interface Methods in C# 8
The output of the above Default Interface Methods program.

In the above program, we can see that we have provided the implementation for the method “DefaultInterfaceMethod” in the interface itself. Here, “MyClass” does not need to implement this method.

Here, we call the “DefaultInterfaceMethod” method with the help of the “IDefaultInterface” interface reference variable. If we try to call the “DefaultInterfaceMethod” method with the class object we will get the following compile-time error.

Change the IDefaultInterface to MyClass, as shown in the below screenshot.

default interface method example in c#
CS1061 ‘MyClass’ does not contain a definition for ‘DefaultInterfaceMethod’ and no accessible extension method ‘DefaultInterfaceMethod’ accepting a first argument of type ‘MyClass’ could be found (are you missing a using directive or an assembly reference?)

The above sample program produces the compile-time error because the “MyClass” does not contain a member “DefaultInterfaceMethod”.
This is proof that the inherited class “MyClass” does not know anything about the default Interface method.
The default interface methods will only work or be accessible if the class is contextually treated as an interface.

To access the default method of the interface, we must upcast the “myClass” object to the “IDefaultInterface” interface as following.

static void Main()
        {
            MyClass myClass = new MyClass();

            //Upcasting to the interface to access the default method
           ((IDefaultInterface)myClass).DefaultInterfaceMethod();            
          
        }

// Output:
// Default method of interface!

Access Modifiers In Interface C# 8.0

Before C# 8.0,Interface members can have implicitly default public access modifier only. Modifiers like  private ,  public ,  protected ,  internal ,  virtual , and  abstract  were not allowed in an Interface.

For additional information on access modifiers in C#, see this link.

Example of Access Modifiers In An Interface

using System;

namespace AccessModifiersInInterface
{
    // Access Modifiers In Interface C# 8.0

    interface IInterface
    {
        // Default Interface method is private by default.
        private void PrivateDefaultMethod()
        {
            Console.WriteLine(" Private Default Method Of Interface!");
        }
        // Public Default Method  
        public void PublicDefaultMethod()
        {
            Console.WriteLine(" Public Default Method Of Interface!");
        }

        //Protected Default Method  
        protected void ProtectedDefaultMethod()
        {
            Console.WriteLine(" Protected Default Method Of Interface!");
        }


        //virtual method
        virtual void VirtualDefaultMethod()
        {
            Console.WriteLine(" Virtual Default method Of Interface!");
        }

        //abstract method having the only declaration

        abstract void AbstractDefaultMethod();

        // static method
        static void StaticDefaultMethod()
        {
            Console.WriteLine(" Static Default Method Of Interface!");
        }

    }

    // A class that implements
    // the "IInterface" interface.
    class MyClass : IInterface
    {
        // Providing implementation
        // part of the abstract method
        void IInterface.AbstractDefaultMethod()
        {
            Console.WriteLine(" Abstract Default Method Of Interface!");
        }

    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine("***** Access Modifiers In Interface C# 8.0 *****");
            IInterface obj = new MyClass();
            //obj.PrivateDefaultMethod(); // inaccessible due to its protection level
            //obj.ProtectedDefaultMethod(); // inaccessible due to its protection level
            obj.PublicDefaultMethod();
            obj.VirtualDefaultMethod();
            obj.AbstractDefaultMethod();
            IInterface.StaticDefaultMethod();

            Console.ReadLine();
        }
    }   
}
// Output:
//*****Access Modifiers In Interface C# 8.0 *****
// Public Default Method Of Interface!
// Virtual Default method Of Interface!
// Abstract Default Method Of Interface!
// Static Default Method Of Interface!
Access Modifiers in Interface C# 8
Access Modifiers in Interface C# 8

Important Points About An ‘Interface In C# 8.0

    • An interface can have only the declarations part is no longer true. After C# 8.0, Interface can implement code for methods, properties, events, or indexers.
    • In C# 8, interface members can have access modifiers such as private, public, protected, internal, virtual, abstract, override, static, and sealed.
    • In C# 8, Interface can have fields, but only if they are static.
    • In C# 8, An interface can have default methods but the derived class inherited by the Interface does not know anything about the existence of the default methods also class does not contain the implementation code of the default method defined in the Interface.
    • The default interface members are not inherited in the derived class in C# 8.

FAQs – Interface vs Abstract class

Can you instantiate an interface in C#?

An interface can’t be directly instantiated in C#. However, we can access the data members of an interface by creating an object of the implementing class and then assign the object to the reference variable of the interface it implements.

Following is a simple example to understand.
FAQ Interface example

Why can’t we instantiate an abstract class in C#?

No, we can’t create an instance of an abstract class because it is an incomplete class. All the members of an abstract class are not fully implemented but partially implemented. We can create an object of a fully implemented class only.

Can an interface have a constructor?

No, Interface can’t have constructors as there are no instance data members (fields) in the interface for initializing through the constructor. Constructors are generally invoked during object creation and we are not allowed to create an instance of the interface So, it doesn’t make sense to have a constructor in an interface.

Why abstract class is used in C# .NET?

An abstract class is generally used to provide a template, blueprint, or a set of some common rules that all the derived classes must follow and implement.
The purpose of the abstract class is to provide the default functionality to all the derived classes. It can contain both abstract and concrete methods that should be open for overriding by the derived classes.

Can we declare the abstract method as static?

No, We can’t declare an abstract method as static because overriding is not possible with the static methods.

Can you inherit multiple interfaces in C#?

Yes, A class can inherit (implement) multiple interfaces in C#.

Is it compulsory for the abstract class to have at least one method as an abstract?

No, it is not necessary to declare an abstract method inside an abstract class.
image result abstract class without abstract method

When to use an abstract class vs interface in C#?

The quick answer is that you can use an abstract class to design functionality that subclasses can implement or override. On the other hand, you can only specify the functionality with an interface, not implement it. A class can extend just one abstract class, but it can extend several interfaces.

Recommended Articles

    1. Generic Delegates in C# With Examples
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. C# Enum | How to Use enumeration type in C#?
    5. Properties In C# with examples
    6. C# Dictionary with Examples
    7. Multithreading in C#
    8. IEnumerable Interface in C# with examples
    9. C# List Class With Examples
    10. C# Struct vs Class

Summary:

In this article, we learned about the ‘difference between the Abstract class and Interface in C#‘ with simple examples. Also, we learned what are the new features in an Interface introduce in C# 8.

I hope you found this post useful in learning about Abstract class and Interface in C#. Your comments, suggestions, and constructive criticism are much appreciated.

2 Replies to “C# Abstract class Vs Interface | 10 differences between Abstract class and Interface with examples”

  1. It’s very good stuff and very easy to understand about when we go for abstract class and when we go for interface.
    Thanks for sharing your knowledge with us.
    Thanks a lot, it’s very helpful for me

Leave a Reply