Home > C# > What is the Difference Between an Abstract Class and an Interface in C#?

What is the Difference Between an Abstract Class and an Interface in C#?


When interviewing for C# jobs often you’ll be asked what is the difference between an abstract class and  interface in C#? In this article, I’ll take a look at these two techniques, their differences and when you should use which one them.

Interfaces in C#

An interface in C# is simply a template for a class. It’s part of how C# implements polymorphism.  An interface doesn’t contain any code, only definitions of methods, properties, events and indexers. A class that implements an interface will need to define the code used for these items. Here’s a short code snippet of an example C# interface…

public interface IMyItem
{
    int Id { get; set; }

    string Description { get; set; }

    string RunTest(int testNumber);

    event EventHandler TestStatus;

    string this[int index] { get; set;}
}

In this example, the interface includes two properties, a method, an event and an indexer. A class that used this interface would need to provide code for these items. While the code doesn’t have to do anything, it does have to be implemented by the class using the interface.

One powerful thing that you can do with interfaces is that you can have a class that implements more than one interface. One of my favorite usages is to not only implement a program specific interface but to also implement a generic List or Queue.

Abstract Classes in C#

An abstract class in C# is a class that can’t be instantiated and, like an interface, is intended to provide a common class definition that is shared by derived classes. Like an interface, the routines in an abstract class may be methods, properties, indexers and events. Unlike an interface, an abstract class may contain code although it may also have abstract methods that do not have code. Also, an abstract class may define constructors and destructors while an interface does not as well as internal private and protected variables.

Here’s a simple example of a C# abstract class…

public abstract class TestItem
{
    private int _testId;

    public TestItem(int testIdValue)
    {
        _testId = testIdValue;
    }

    public int TestId
    {
        get
        {
            return _testId;
        }
        set
        {
            _testId = value;
        }
    }

    public abstract string Description { get; set; }

    public abstract void RunTest(int i);

    public abstract string this[int index] { get; set; }
}

As you can see above, there is code in the constructor and one of the properties while the rest of the routines are marked with the abstract keyword to indicate that their implementation is left up to the derived subclass. The routines marked as abstract have to be implemented in code by the derived class, they aren’t optional. However, the routines that are implemented in code by the abstract class do not have to be implemented in code by the subclass. However, routines that have code in the abstract class can be overridden if they’re marked with the virtual keyword.

Here’s an example of a class that is derived from the abstract class above…

public class Tester : TestItem
{
    public Tester(int testIdValue) : base(testIdValue) { }

    public override string Description { get; set; }

    public override void RunTest(int i)
    {
        //call test routines
    }

    public override string this[int index]
    {
        get
        {
            // process and return some data
        }
        set
        {
            // process and assign some data
        }
    }
}

Note that we need to use the override keyword to indicate to the Framework that a particular routine is overriding the base abstract class’ routine definition. Also see that the class doesn’t have an implementation of TestId property, it uses the code in the abstract class instead. One tricky part is in our constructor. We have to define a constructor or else the compiler will present this error: “[classname] does not contain a constructor that takes 0 arguments”. To avoid this error, we have to define a constructor and pass the value on to the base class code as seen in the example code above.

Abstract Class vs. Interface in C#

But, when should you use an abstract class instead of an interface and vice versa? Either technique provides a way to have a common definition for a class although interfaces are a form of polymorphism and abstract classes are a form of inheritance, from an OOP perspective. Let’s see what this means in practical terms.

Let’s assume that we’re working on an inventory and invoicing system that has several different user types, such as vendor, dealer, distributor, employee and so forth. As we look at the system, it’s obvious we’ll be handling users will be the same for all users so it makes sense to have a user abstract class that we can derive our classes from for our various types. In this context, an interface probably wouldn’t make sense because there would probably be similar implementation needs across the spectrum of users. So, we might have an abstract base class called User that would have subclasses for each type of user.

Now, let’s assume that in our system we wanted to standardize how programmers working on the project defined common functions such as duplicating records. On a large project, it can get confusing with everybody defining things their own way, so, by using a common interface standard a lot of this confusion can be eliminated. For example, an IDuplicate interface could be used for users, invoices, inventory items and so forth in the project. The actual code might be considerably different but the interface is the same across the board in the project. Also, remember that C# is single inheritance, you can include more than one interface. Therefore, a class could implement an IDuplicate interface as well as other interfaces you might define or ones that you might borrow from the .NET Framework, such as IList.

I hope this has helped you get the differences between abstract classes and interfaces in C# clearer in your mind.

Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: