Monday, September 21, 2020

When to use abstract class and interface in C#?

Differences between an abstract class and interface in real projects for achieving loosely coupled design patterns and SOLID principles.



There are 1000+ articles on this subject, but here my goal of writing this article is to understand when to use abstract class and interface in real-world applications.

When we go for an interview most of your face this question, so don’t worry, here I’m trying my best to explain to you in a simple way with real examples. This will help to give an answer very confident at the time of the interview.

[Top 100+ popular C# Interview Questions and Answers.]

When you start designing real-world applications a question comes to your mind, what should I use abstract class or interface? Let’s start with some basic understanding of abstract class and interface.

In short, we can say that the abstract class allows implementing both methods abstract and non-abstract, where interface allows only abstract methods (declaration of the method), and multiple inheritances are possible with an interface.

C# abstract class understanding and the key point

  1. Abstraction is the process of hiding the internal details and showing only the functionality.
  2. An abstract class declares with an abstract keyword.
  3. An abstract class may or may not abstract method and properties.
  4. Can’t create an object of an abstract class.
  5. An abstract method has no body (only declaration of method).
  6. An abstract class is used to define a base class in the class hierarchy.
  7. An abstract method must be implemented within a derived class.
  8.  An abstract method never declares as a private modifier.
  9. Users must use the override keyword in the child class to implement the abstract methods.
  10. An abstract class can’t have constructors or destructors.
  11. It can support implementation within the non-abstract method.
  12. An abstract class can’t declare as static.
  13. Class can’t implement multiple abstract class

C# interface understanding and the key point

  1. We can achieve abstraction using the interface.
  2. An interface contains an only declaration of the method (fully abstract class) not implementation.
  3. The  Method must be implemented within derive class.
  4.   The method has no any access modifier by default public.
  5.   A class can implement multiple interfaces.
  6.   We do not have to use override keyword when implementing it in the derived class.
  7.   An interface cannot contain fields and auto-implemented properties.  Use public modifier when implementing an interface implicitly, whereas don’t use it in case of explicit implementation.

Example of an implicit interface:

              interface IFile

              {

                     string ReadFile();

              }

              class FileInfo : IFile

              {

                     public string ReadFile()

                     {

                            return "Reading Text File";

                     }

              }

Example of an explicit interface:

        interface IFile

              {

                     string ReadFile();

              }

              interface IBinaryFile

              {

                     string OpenBinaryFile();

                     string ReadFile();

              }

             

              class FileInfo : IFile, IBinaryFile

              {

                     string IFile.ReadFile()

                     {

                            return "Reading Text File";

                     }


                      string IBinaryFile.OpenBinaryFile()

                      {

                           return "Opening Binary File";

                      }

 

                     string IBinaryFile.ReadFile()

                     {

                           return "Reading Binary File";

                     }

              }

So here the question is that what should we use interface or abstract class?

So I will start with one real-world example, if you have ever visited an amusement park you have seen that there are some rides with safety precaution. Who can use the ride?

Look into the above image very carefully and let’s consider the first criteria. There are some predefined rules to use some ride. Visitors must within these criteria first, after that the visitors are free to enjoy those ride numbers of times as per visitor's wish.

And let’s consider the second criteria. There are some rides there are no predefined rules to visit those rides, so every visitor is free to enjoy those rides a number of times as per visitors wish.

Abstract class vs. Interface

Now let’s compare this example with an abstract class and interface. The first criteria are our abstract class. In abstract class, there is some non-abstract method which is a predefined method. Child class must follow that implementation for use this method, but some method is an abstract method so child class is free to implement those methods as per their need.

The second criteria are our interface. In an interface all method is non-abstract so child class is free to implement as per their need.

Now we try to understand with our real-time application in C#.

When and How to Use Abstract class In Real-Time Application or Project?

Abstract Class: An abstract class is a good choice of plans for future expansion. Because an abstract class provides the facility to create some concrete methods and other methods must implement by the derived class.

Now take the example of Cars class. Cars have some common functionality so this class considers as parent class and Volkswagen class is a child class derived from the base class Cars. It looks like below.

public abstract class Cars

    {

        public string NoOfWheel()

        {

            return "4 wheeler.";

        }

        public string ACFacility()

        {

            return "AC is available.";

        }

        public string CallFacility()

        {

            return "Call is available.";

        }

        public abstract string DiscountPrice();

    }

    public class Volkswagen : Cars

    {

        public override string DiscountPrice()

        {

            return "5% discount on buying Toyoya Cars";

        }

    }

Here we can see there is some common method which is available in all cars of Volkswagen but the discount is differed model by model, so the discount method is declared as an abstract method, so it will implement by child classes based on the car model and company.

When and How to Use Interface in Real-Time Application or Project?

Interface: Interface is a contract for the child classes to all the methods must implement which is declared in an interface. As we know in an interface we can only declare non-abstract methods. An interface allows multiple inheritances in C# that is also an advantage compared to an abstract class.

interface INewFeatures

    {

        string IsGPS();

    }

    public class Volkswagen : Cars, INewFeatures

    {

        public override string DiscountPrice()

        {

            return "5% discount on buying Toyoya Cars";

        }

        public string IsGPS()

        {

            return "GPS is available."

        }

    }

Here we have used interface for new features, because if we use an abstract class instead of an interface, it will throw an error, due to multiple inheritances not support in C#. We inherit the INewFeatures interface in those car model classes who support the GPS system, so in this scenario interface is best practice.

Conclusion:

When we have a requirement of the class who contains some common properties or methods, but the implementation differs from class to class, and some methods or properties whose implementation common for all the classes, in that case, use an abstract class where implementation is different for each class then go for an interface.

I hope you have liked the article to understanding of when to use abstract class and when to use interface in C#.

Please feel free to comment if you have found anything incorrect, or you want to share more information about the topic discussed above.

Please Share this article so it will helpful to another one because “Helping millions grow better”.

Follow my blog https://mydotnetguru.blogspot.com/ to read the more interesting article.

Next Recommended Article:

  1. Async and Await in C#
  2. Optimized top 2 ways to find 2nd or Nth highest salary in SQL Server.
  3. Different ways to remove or delete duplicate rows from a SQL Table.
  4. Top 100+ popular ASP.Net MVC Interview Questions and Answers.
  5. Top 100+ popular C# Interview Questions and Answers.
  6. Top 100+ popular SQL Interview Questions and Answers Blog.
  7. @Input, @Output decorator and EventEmitter class in Angular.
  8. Dependency Injection and types of dependency injection.

No comments:

Post a Comment