72

"Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however, this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes instead of interfaces with extension methods?

A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via a multitude of extension methods.

6
  • 2
    And we can use 'Properties' in interfaces also.
    – Gulshan
    Commented Jan 31, 2011 at 9:19
  • 1
    Sounds like a C# specific rather than a general OOD question. (Most other OO languages don't have extension methods nor properties.) Commented Jan 31, 2011 at 9:39
  • 1
    stackoverflow.com/questions/2308786/…
    – Gopi
    Commented Jan 31, 2011 at 10:12
  • 4
    Extension methods do not quite solve the problem that the abstract classes solve, so the reason is no different than it is in Java or some other similar single-inheritance language.
    – Job
    Commented Dec 13, 2011 at 16:09
  • 3
    The need for abstract class method implementations has not been reduced by extension methods. Extension methods cannot access private member fields, nor can they be declared virtual and be overridden in derived classes.
    – zooone9243
    Commented Aug 25, 2012 at 15:25

7 Answers 7

63
+50

When you need a part of the class to be implemented. The best example I've used is the template method pattern.

public abstract class SomethingDoer
{
    public void Do()
    {
        this.DoThis();
        this.DoThat();
    }

    protected abstract void DoThis();
    protected abstract void DoThat();
}

Thus, you can define the steps that will be taken when Do() is called, without knowing the specifics of how they will be implemented. Deriving classes must implement the abstract methods, but not the Do() method.

Extensions methods don't necessarily satisfy the "must be a part of the class" part of the equation. Additionally, iirc, extension methods cannot (appear to) be anything but public in scope.

edit

The question is more interesting than I had originally given credit for. Upon further examination, Jon Skeet answered a question like this on SO in favour of using interfaces + extension methods. Also, a potential downside is using reflection against an object hierarchy designed in this way.

Personally, I am having trouble seeing the benefit of altering a currently common practice, but also see few to no downsides in doing it.

It should be noted that it is possible to program this way in many languages via Utility classes. Extensions just provide the syntactic sugar to make the methods look like they belong to the class.

7
  • Beat me to it..
    – Giorgi
    Commented Jan 31, 2011 at 10:18
  • 1
    But same thing can be done with Interfaces and extension methods. There the methods you are defining in the abstract base class like Do() will be defined as an extension method. And the methods left for derived classes' definition like DoThis() will be member of the main Interface. And with interfaces, you can support multiple implementations/inheritance. And see this- odetocode.com/blogs/scott/archive/2009/10/05/…
    – Gulshan
    Commented Jan 31, 2011 at 10:53
  • @Gulshan: Because a thing can be done in more than one way does not make the chosen way invalid. There is no advantage in using interfaces. The abstract class itself is the interface. You don't need interfaces to support multiple implementations.
    – ThomasX
    Commented Dec 13, 2011 at 14:06
  • Also, there can be disadvantages to the interface + extension model. Take the Linq library, for instance. It's great, but if you need to use it only once in that code file, the full Linq library will be available in IntelliSense on EVERY IEnumerable in your code file. This can slow IDE performance considerably.
    – KeithS
    Commented Feb 2, 2012 at 19:22
  • -1 because you have not demonstrated any way in which abstract classes are a better fit for Template Method than interfaces Commented Jan 28, 2015 at 21:50
26

It's all about what you want to model:

Abstract classes work by inheritance. Being just special base classes, they model some is-a-relationship.

For example, a dog is an animal, thus we have

class Dog : Animal { ... }

As it doesn't make sense to actually create a generic all-animal (what would it look like?), we make this Animal base class abstract - but it's still a base class. And the Dog class doesn't make sense without being an Animal.

Interfaces on the other hand are a different story. They don't use inheritance but provide polymorphism (which can be implemented with inheritance too). They don't model an is-a relationship, but more of a it does support.

Take e.g. IComparable - an object that supports being compared with another one.

The functionality of a class does not depend on the interfaces it implements, the interface just provides a generic way of accessing the functionality. We could still Dispose of a Graphics or a FileStream without having them implement IDisposable. The interface just relates the methods together.

In principle, one could add and remove interfaces just like extensions without changing the behaviour of a class, just enriching the access to it. You cannot though take away a base class as the object would become meaningless!

4
  • When would you choose to keep a base class abstract?
    – Gulshan
    Commented Jan 31, 2011 at 12:28
  • 1
    @Gulshan: If it does - for some reason - not make sense to actually create an instance of the base class. You can "create" a Chihuahua or a white shark, but you cannot create an animal without further specialization - thus you would make Animal abstract. This enables you to write abstract functions to be specialized by the derived classes. Or more in programming terms - it does probably make no sense to create a UserControl, but as a Button is a UserControl, so we have the same kind of class/baseclass relationship.
    – Dario
    Commented Feb 1, 2011 at 21:05
  • if you have abstract methods, than you have abstract class. And abstract methods you have when there is no value for implementing them (like "go" for animal). And of course sometimes you don't want to allow objects of some general class, than you make it abstract.
    – Dainius
    Commented Jun 15, 2011 at 11:33
  • There is no rule that says that if it's grammatically and semantically meaningful to say "B is an A" then A must be an abstract class. You should prefer interfaces until you really can't avoid the class. Sharing code can be done via composition of interfaces, etc. It makes it easier to avoid painting oneself into a corner with weird inheritance trees.
    – sara
    Commented May 8, 2016 at 8:17
4

I just realized, that I haven't used abstract classes (at least not created) in years.

Abstract class is a somewhat strange beast between interface and implementation. There is something in abstract classes which tingles my spider-sense. I would argue, one should not "expose" the implementation behind interface in any way (or make any tie-ins).

Even if there is a need for common behavior between classes implementing an interface, I would use an independent helper class, rather than an abstract class.

I would go for interfaces.

2
  • 2
    -1: I'm not sure how old you are, but you might want to learn design patterns, particularly the template method pattern. Design patterns will make you a better programmer and they'll end your ignorance of abstract classes.
    – Jim G.
    Commented Feb 23, 2011 at 18:00
  • Same about the tingling sensation. Classes, the first and foremost feature of C# and Java, are a feature for creating a type and immediately chaining it forever to one implementation. Commented Feb 24, 2011 at 17:03
2

IMHO, I think that there is a mixing of concepts here.

Classes use a certain kind of inheritance, while interfaces use a different kind of inheritance.

Both kinds of inheritance are important and useful, and each one has its pros and cons.

Let's start at the beginning.

The story with interfaces starts a long while back with C++. In the mid-1980s, when C++ was developed, the idea of interfaces as a different kind of type was not yet realized (it would come in time).

C++ only had one kind of inheritance, the kind of inheritance used by classes, called implementation inheritance.

To be able to apply the GoF Book recommendation: "To program for the interface, and not for the implementation", C++ supported abstract classes and multiple implementation inheritance to be able to do what interfaces in C# are capable (and useful!) of doing.

C# introduces a new kind of type, interfaces, and a new kind of inheritance, interface inheritance, to offer at least two different ways to support "To program for the interface, and not for the implementation", with one important caveat: C# only supports multiple inheritance with interface inheritance (and not with implementation inheritance).

So, the architectural reasons behind interfaces in C# is the GoF recommendation.

I hope this can be of help.

Kind regards, Gastón

1

Applying extension methods to an interface is useful for applying common behaviour across classes that may share only a common interface. Such classes may already exist and be closed to extensions via other means.

For new designs I would favour the use of extension methods on interfaces. For a hierarchy of Types, extension methods provide a means to extend behaviour without having to open the entire hierarchy for modification.

However, extension methods are unable to access private implementation, so at the top of a hierarchy, if I need to encapsulate private implementation behind a public interface then an abstract class would be the only way.

3
  • No, it's not the only safe way. There is another safer way. That is the extension methods. Clients will not be infected at all. That's why I have mentioned interfaces + extension methods.
    – Gulshan
    Commented Jan 31, 2011 at 11:36
  • @Ed James I think "less powerful" = "more flexible" When would you choose a more powerful abstract class instead of more flexible interface?
    – Gulshan
    Commented Jan 31, 2011 at 12:26
  • @Ed James In asp.mvc extension methods were used from the very beginning. What do you think about that?
    – Gulshan
    Commented Feb 23, 2011 at 11:08
0

I think that in C# multiple inheritance is not supported and that's why concept of interface is introduced in C#.

In case of abstract classes, multiple inheritance is not supported either. So it is easy to decide on wether to use abstract classes or interfaces.

1
  • To be precise, it's pure abstract classes that are called "interfaces" in C#. Commented May 16, 2014 at 21:47
-1

I'm in the process of implementing an Abstract class in my project simply because C# does not support operators (implicit conversions, in my case) on Interfaces.

Not the answer you're looking for? Browse other questions tagged or ask your own question.