C# Abstract class Vs Interface: Uses And Differences 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 asked questions in almost every C# dot net interview.

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

C# Abstract class Vs Interface

In Short, An abstract class allows you to create functionality that subclasses can implement or override. An interface, on the other hand, only allows you to define functionality rather than implement it. In addition, While a class can extend only one abstract class, but can have multiple interfaces.

  • The abstract class and interface are used to achieve abstractions. In C#, Abstraction is the process of defining the essential details to call methods without exposing the implementation details.
  • If complex functional units are not your objective, an interface might be more appealing. Use abstract classes if you want to extend the class hierarchy in the future

Both abstract class and interface have their own advantages and disadvantages. So, without further ado, let us take a closer look at the abstract class and interface in depth.

First, Let`s take a look at the following list of differences between the abstract class and the interface.

Sr.No.Abstract ClassInterface
01.In C#, An Abstract class can have public, private, or protected class members.However, every method, property, and event contained within an Interface is always public by default.
02.An abstract class in C# can contain constructors.An interface in C# can’t contain a constructor
03.Abstract classes do not support multiple InheritanceOn the other side, the Interface supports multiple Inheritance in C#.
04.A class can be inherited by only one abstract class.A class can inherit by multiple interfaces.
05.An abstract class in C# can be fully implemented, partially implemented, or not implemented at all.An interface contains only the signatures of methods, properties, events, or indexers not the implementation.
06.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.
07.An abstract class can contain both declaration and Implementation of methods.An interface is used when you only need the signature of a method and not the implementation.
08.An abstract class can contain fields and constants.An interface cannot have fields.
09.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 the 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 interface and abstract class

C# Abstract class

Abstract class: In C#, An abstract class is a way to achieve abstraction, which is intended to hide the internal details and show 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.

  • An abstract class can have both abstract and concrete methods, So either it can be partially implemented or not implemented at all. It is mainly designed to be inherited by subclasses that either implement or override its methods.

When to use an Interface in C#?

Below is the list of reasons for using the interface in C#.

  • A C# Interface allows for multiple Inheritance. A class, however, cannot inherit from more than one abstract class.
  • 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.
  • Interfaces are best suited to achieve Dispose Pattern by defining an  IDisposable  interface.
  • An Interface doesn’t contain a constructor, which helps to prevent extra roundtrip when creating an object of the derived class through the reference pointer of the interface.
  • An Interface can be a great choice when we want to loop through a collection for example by using an  IEnumerable  interface.
  • Your application will be easier to test and maintain if you use an interface. It helps to define a contract, or agreement, between your application and other objects. This agreement specifies the methods, fields, properties, and events an object exposes.

You should use an interface if you want a contract on some behavior or functionality to be strictly followed by the subclass or struct. If you use interfaces, you must implement all of the methods in the subclass that extends the interface.

  • Interfaces may be a good choice to decouple your application’s code from specific implementations as different classes can implement methods differently.
  • You can also use an interface if you want to simulate inheritance for structs because structs cannot inherit from another struct or class in C#.

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

This is one of the most frequently asked questions in C# dot-net interviews. Most developers are still not completely sure of the right answer. The following examples are used to illustrate these concepts.

  • The Abstract classes offer default functionality for the derived classes.
  • An abstract class 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. We must create a new interface if we want to add a new method to the 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 for 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 the 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 the 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 contain 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 the default interface method

The following is a 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#
Error message: 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 follows.

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 Key Points About An Interface In C# 8.0

  • An interface can have only the declarations part that is no longer true. After C# 8.0, the 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, the 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.

To learn more about Interface, please refer to this article: C# 10 new features

FAQ

Q: 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 assigning the object to the reference variable of the interface it implements.

The following is a simple example to understand.
FAQ Interface example

Q: 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.

Q: Can an interface have a constructor?

No, the 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.

Q: Why abstract class is used in C# .NET?

An abstract class is generally used to provide a template, blueprint, or a set of 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.

Q: Can we declare the abstract method as static?

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

Q: Can you inherit multiple interfaces in C#?

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

Q: 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

Q: 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.

References: InfoWorld- Abstract class Vs Interface

Summary:

In this article, we learned about the ‘difference between the Abstract class and Interface in C#‘ with simple examples. Also, we learned the new features in an Interface introduced 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.

Recommended Articles:

We would love to hear your thoughts on this post. Please leave a comment below and share it with others.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
5 2 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Vaishali
Vaishali
1 year ago

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

Lucas
Lucas
4 months ago

This post was very useful, it explained abstract class and interface in a simple way and included real examples which helped a lot. Thank you for sharing your expertise.