172

I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

2

19 Answers 19

163

They are there just to make sure that the said functions (in the interface) are implemented in the inheriting class.

Correct. That's a sufficiently awesome benefit to justify the feature. As others have said, an interface is a contractual obligation to implement certain methods, properties and events. The compelling benefit of a statically typed language is that the compiler can verify that a contract which your code relies upon is actually met.

That said, interfaces are a fairly weak way to represent contractual obligations. If you want a stronger and more flexible way to represent contractual obligations, look into the Code Contracts feature that shipped with the last version of Visual Studio.

C# is a great language, but sometime it gives you the feeling that first Microsoft creates the problem(not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

Well I'm glad you like it.

All complex software designs are a result of weighing conflicting features against each other, and trying to find the "sweet spot" that gives large benefits for small costs. We've learned through painful experience that languages that permit multiple inheritance for the purposes of implementation sharing have relatively small benefits and relatively large costs. Permitting multiple inheritance only on interfaces, which do not share implementation details, gives many of the benefits of multiple inheritance without most of the costs.

7
  • I was just reading "Microsoft creates the problem by not allowing multiple inheritance" and I thought Eric Lippert would have something to say about that. Commented Sep 14, 2011 at 17:07
  • More relevant to this answer: Eric, you're referring the asker to Code Contracts, but they are woefully incomplete; anything other than the most basic contracts is not enforceable by the static checker. I tried using Code Contract on a small project; I've added hundreds of lines for each and every method specifying everything I could about input and output, and yet, I had to add so many Assume calls, for cases like array or enumeration members. After adding everything and seeing the statically verified mess I had, I reverted in source control because it reduced the quality of my project. Commented Sep 14, 2011 at 17:11
  • 17
    @configurator: They are incomplete because they cannot be complete; static program verification with arbitrary contracts is equivalent to solving the Halting Problem. (For example, you could write a code contract that says that the arguments to a method must be a counterexample to Fermat's Last Theorem; but the static verifier is not going to be able to verify that there are no such arguments.) You've got to use it judiciously if you expect the static verifier to complete its work before the heat death of the universe. (If your complaint is that the BCL is insufficiently annotated: I agree.) Commented Sep 14, 2011 at 17:23
  • 2
    I expect it to realize that when one method promises that the results array or enumeration does not contain null, the using method can use the values in places that don't allow nulls. That's the one thing I expected it to do that it didn't, and it was too important to be usable without it; anything else is just a bonus. That said, I know static verification can't be complete, which is why I think it's not a good alternative to rely on for contracts. Commented Sep 14, 2011 at 17:27
  • 9
    +1 for "Well I'm glad you like it." And all the other stuff too.
    – Robert S.
    Commented Sep 15, 2011 at 16:33
247

enter image description here

So in this example, the PowerSocket doesn't know anything else about the other objects. The objects all depend on Power provided by the PowerSocket, so they implement IPowerPlug, and in so doing they can connect to it.

Interfaces are useful because they provide contracts that objects can use to work together without needing to know anything else about each other.

7
  • 4
    The bottom left object doesn't look like it implements IPowerPlug =) Commented Sep 20, 2011 at 20:21
  • 105
    Damn, but we'll have to use an Adapter pattern in order to use the IPowerPlug in different countries! Commented Sep 20, 2011 at 22:17
  • Jerry-rigging a device to work around the interface is not safe (but some people still do it often citing performance as an untested excuse), and likely to lead to fires.
    – YoungJohn
    Commented Aug 11, 2015 at 14:28
  • 6
    This answer is just amazing... Commented Feb 22, 2018 at 11:29
  • Just pointing out this answer doesn't say - in this particular example - why using an interface would be preferable over inheritance. Someone new to interfaces might ask why they don't all just inherit from e.g. MainsPoweredDevice that provides all the plug functionality, with the socket accepting anything derived from MainsPoweredDevice. Commented Sep 26, 2019 at 5:48
145

Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them

The point of interfaces is not to help you remember what method to implement, it is here to define a contract. In foreach P.Brian.Mackey example (which turns out to be wrong, but we don't care), IEnumerable defines a contract between foreach and any enumerable thing. It says : "Whoever you are, as long as you stick to the contract (implement IEnumerable), I promise you I'll iterate over all your elements". And, that is great (for a non dynamic language).

Thanks to interfaces you can achieve very low coupling between two classes.

4
  • We're discussing this answer in chat.
    – Daniel
    Commented Sep 15, 2011 at 16:13
  • I dislike using the term "duck typing" because it means different things to different people. We use pattern matching for the "foreach" loop because when it was designed, IEnumerable<T> was unavailable. We use pattern matching for LINQ because the C# type system is too weak to capture the "monad pattern" we need; you'd need something like the Haskell type system. Commented Sep 15, 2011 at 17:40
  • @Eric: Doesn't "pattern matching" have the same problem? When I hear it I think F#/Scala/Haskell. But I guess it's a broader idea than duck-typing.
    – Daniel
    Commented Sep 15, 2011 at 18:26
  • @Daniel: Yeah, I suppose it does. Its six of one and half a dozen of the other I guess! Commented Sep 15, 2011 at 18:27
37

Interfaces are the best way to maintain well decoupled constructs.

When writing tests, you will find that concrete classes will not work in your test environment.

Example: You want to test a class that depends on a Data Access Service class. If that class is talking to a web service, or database -- your unit test will not run in your test environment ( plus it has turned into an integration test ).

Solution? Use an Interface for your Data Access Service and Mock that interface so you can test your class as a unit.

On the other hand, WPF & Silverlight do not play at all with Interfaces when it comes to binding. This is a pretty nasty wrinkle.

1
  • 2
    hear hear! Interfaces were invented to solve other problems, such as polymorphism. However, for me, they come into their own when implementing a Dependency Injection pattern.
    – andy
    Commented Sep 15, 2011 at 5:17
30

Interfaces are the backbone of (static) polymorphism! The interface is what matters. Inheritance would not work without interfaces, as subclasses basically inherit the already implemented interface of the parent.

How often you make uses of them and what makes you do so ??

Pretty often. Everything that needs to be pluggable is an interface in my applications. Often times you have otherwise unrelated classes that need to provide the same behaviour. You can't solve such problems with inheritance.

Need different algorithms to perform operations on the same data? Use an interface (see strategy pattern)!

Do you want to use different list implementations? Code against an interface and the caller does not need to worry about the implementation!

It's been considered a good practice (not only in OOP) to code against interfaces for ages, for one single reason: It's easy to change an implementation when you realize it does not fit your needs. It's pretty cumbersome if you try to achieve that only with multiple inheritance or it boils down to creating empty classes in order to provide the necessary interface.

15
  • 1
    Never heard of polymorphy, you mean polymorphism? Commented Sep 14, 2011 at 14:13
  • 1
    that being said, if microsoft allowed multiple inheritance in the first place, there would have been no reason for existence of interfaces Commented Sep 14, 2011 at 14:15
  • 11
    @Pankaj Upadhyay: Multiple inheritance and interfaces are two different pairs of shoes. What if you need an interface of two unrelated classes with different behaviour? You can't solve that by multiple inheritance. You HAVE TO implement it separately anyway. And then you'll need something to describe the interface in order to provide polymorphic behaviour. Multiple inheritance is a blind alley to walk down in many cases, and it's too easy to shoot yourself in the foot sooner or later.
    – Falcon
    Commented Sep 14, 2011 at 14:17
  • 1
    Lets simplify. If my interface implements two functions Display and Comment, and I have a class which implements them. Then why not I remove the interface and use the functions directly. What i am saying is that they are merely providing you the names of the functions that are needed to be implemented. If one can remember those functions then why create an interface Commented Sep 14, 2011 at 14:25
  • 9
    @Pankaj, if that is all that you need the interface for, then don't use it. YOu use an interface when you have a program that wants to be ignorant of every aspect of the class and access it by its base Type, i.e. the interface. They don't need to know any of the subclasses, just that it is of the type of the interface. As such, you can then call the implemented method of the sub-class through the reference to the object's interface. This is basic inheritance and design stuff. Without it, you might as well use C. Even if you don't explicitly use it, the framework would not work without it. Commented Sep 14, 2011 at 14:33
12

You have probably used foreach and found it to be a pretty useful iteration tool. Did you know that it requires an interface to function, IEnumerable?

That's certainly a concrete case speaking to the usefulness of an interface.

5
  • 5
    Actually, foreach does not require IEnumerable: msdn.microsoft.com/en-us/library/9yb8xew9%28VS.80%29.aspx
    – Matt H
    Commented Sep 14, 2011 at 14:15
  • 1
    I have studied all that but it's like holding the ear with other hand. If multiple inheritace was allowed, interface would have been a far choice. Commented Sep 14, 2011 at 14:17
  • 2
    Interfaces ARE multiple inheritance, something that is often forgotten. However, they do not allow multiple inheritance of behavior and state. Mixins or traits allow multiple inheritance of behavior, but not shared state which causes issues: en.wikipedia.org/wiki/Mixin
    – Matt H
    Commented Sep 14, 2011 at 14:53
  • @Pankaj, offtopic, but do you mind if I ask what your native language is? "Holding the ear with the other hand" is a great idiom and I was curious where it comes from.
    – Kevin
    Commented Sep 14, 2011 at 15:05
  • 3
    @Iceman. LOL....I am from india. And here it is a common idiom which reflects doing easy things the difficult way. Commented Sep 14, 2011 at 17:34
11

Interfaces are to coding objects like a plug is to household wiring. Would you solder your radio directly to your house wiring? How about your vacuum cleaner? Of course not. The plug, and the outlet it fits into, form the "interface" between your house wiring and the device that needs the power from it. Your house wiring needs to know nothing about the device other than it uses a three-prong grounded plug and requires electrical power at 120VAC <=15A. Conversely, the device requires no arcane knowledge of how your house is wired, other than that it has one or more three-prong outlets conveniently located that provide 120VAC <=15A.

Interfaces perform a very similar function in code. An object can declare that a particular variable, parameter or return type is of an interface type. The interface can't be instantiated directly with a new keyword, but my object can be given, or find, the implementation of that interface that it will need to work with. Once the object has its dependency, it doesn't have to know exactly what that dependency is, it just has to know it can call methods X, Y and Z on the dependency. Implementations of the interface don't have to know how they will be used, they just have to know they will be expected to provide methods X, Y and Z with particular signatures.

Thus, by abstracting multiple objects behind the same interface, you provide a common set of functionality to any consumer of objects of that interface. You don't have to know the object is, for example, a List, a Dictionary, a LinkedList, an OrderedList, or whatever. Because you know all of these are IEnumerables, you can use the methods of IEnumerable to go through each element in these collections one at a time. You don't have to know that an output class is a ConsoleWriter, a FileWriter, a NetworkStreamWriter, or even a MulticastWriter that takes other types of writers; all you have to know is that they're all IWriters (or whatever), and thus they have a "Write" method that you can pass a string into, and that string will be output.

7

While it clearly is a treat for the programmer (at first, at least) to have multiple inheritance, this is an almost trivial omission, and you should (in most cases) not rely on multiple inheritance. The reasons for this are complex, but if you really want to learn about it, consider the experience from the two most famous (by TIOBE index) programming languages that support it: C++ and Python (3rd and 8th respectably).

In Python, multiple inheritance is supported, yet is almost universally misunderstood by programmers and to state that you know how it works, means to read and understand this paper on the topic: Method Resolution Order. Something else, that happend in Python, is that interfaces sort-of-got into the language - Zope.Interfaces.

For C++, google "diamond hierarchy C++" and behold the ugliness that is about to cover you. C++ pros know how to use multiple inheritance. Everybody else is usually just playing around without knowing what the results will be. Another thing that shows how useful are interfaces is the fact, that in many cases a class might need to override completely its parent's behavior. In such cases, the parent implementation is unnecessary and only burdens the child class with the memory for the parent's private variables, which might not matter in the C# age, but matters when you do embedded programming. If you use an interface, that problem is nonexistent.

In conclusion, interfaces are, in my opinion, an essential part of OOP, because they enforce a contract. Multiple inheritance is useful in limited cases, and usually only to guys who know how to use it. So, if you are a beginner, you are the one who is treated by the lack of multiple inheritance - this gives you a better chance to not make a mistake.

Also, historically, the idea for an interface is rooted far earlier than Microsoft's C# design specs. Most people consider C# to be an upgrade over Java (in most senses), and guess where C# got its interfaces from - Java. Protocol is an older word for the same concept, and it is way older than .NET.

Update: Now I see I might have answered a different question - why interfaces instead multiple inheritance, but this seemed like the answer you were looking. Besides an OO language should have at least one of the two, and the other answers have covered your original question.

6

It's difficult for me to imagine clean, object-oriented C# code without the use of interfaces. You use them whenever you wish to enforce the availability of certain functionality without forcing classes to inherit from a specific base class, and this allows your code to have the relevant level of (low) coupling.

I don't agree that multiple inheritence is better than having interfaces, even before we get to arguing that multiple inheritence comes with it's own set of pains. Interfaces are a basic tool for enabling polymorphism and code reuse, what more does one need?

5

I personally love the abstract class and use it more than an interface. The main difference comes with integrating with .NET interfaces such as IDisposable, IEnumerable and so on... and with COM interop. Also, the interface is a little less effort to write than an abstract class, and a class can implement more than one interface while it can only inherit from one class.

That said, I find that most things I would use an interface for are better served by an abstract class. Pure virtual functions--abstract functions-- allow you to force an implementer to define a function similar to the way an interface forces an implementer to define all of its members.

However, you typically use an interface when you do not want to impose a certain design upon the super class, while you would use an abstract class to have a reusable design that is already mostly implemented.

I have used interfaces extensively with writing plugin environments using the System.ComponentModel namespace. They come quite in handy.

1
5

I can say I relate to that. When I first started learning about OO and C# I too didn't get Interfaces. That's ok. We just need to come accross something that will make you appreciate the conveniences of interfaces.

Let me try two approaches. And pardon me for the generalizations.

Try 1

Say you're a native English speaker. You go to another country where English is not the native language. You need help. You need someone who can help you.

Do you ask: "Hey, were you born in the United States?" This is inheritance.

Or do you ask: "Hey, do you speak English"? This is interface.

If you care about what it does, you can rely in interfaces. If you care about what is is, you rely on inheritance.

It's ok to rely on inheritance. If you need someone who speaks English, likes tea and likes soccer, you're better served asking for a Brit. :)

Try 2

Ok, let's try another example.

You use different databases and you need to implement abstract classes to work with them. You'll pass your class to some class from the DB vendor.

public abstract class SuperDatabaseHelper
{
   void Connect (string User, string Password)
}

public abstract class HiperDatabaseHelper
{
   void Connect (string Password, string User)
}

Multiple inheritance, you say? Try that with the above case. You can't. The compiler won't know which Connect method you're trying to call.

interface ISuperDatabaseHelper
{
  void Connect (string User, string Password)
}

interface IHiperDatabaseHelper
{
   void Connect (string Password, string User)
}

Now, there's something we can work with - at least in C# - where we can implement interfaces explicitly.

public class MyDatabaseHelper : ISuperDatabaseHelper, IHiperDatabaseHelper
{
   IHiperDataBaseHelper.Connect(string Password, string User)
   {
      //
   }

   ISuperDataBaseHelper.Connect(string User, string Password)
   {
      //
   }

}

Conclusion

The examples are not the best, but I think it gets the point accross.

You'll only "get" interfaces when you feel the need of them. Until them you'll think they're not for you.

3
  • The first Try is what gave my vote.
    – osundblad
    Commented Jan 29, 2013 at 21:32
  • 1
    I am totally using the American vs. English Speaker analogy from now on. That is fantastic.
    – Bryan B
    Commented Jan 11, 2018 at 20:35
  • Explained in a simpler way! Fantastic.
    – Aimal Khan
    Commented Aug 31, 2018 at 2:41
4

Interfaces by themselves are not very useful. But when implemented by concrete classes you see that it gives you the flexibility to have one or more implementations. The bonus is that the object using the interface do not need to know how the details of the actual implementation go - that's called encapsulation.

4

There are 2 major reasons:

  1. Lack of multiple inheritance. You can inherit from one base class and implement any number of interfaces. That's the only way to "do" multiple inheritance in .NET.
  2. COM interoperability. Anything that will need to be used by "older" technologies will need to have interfaces defined.
2
  • Point 1 is definitely the reason and the reason developed by microsoft developers themselves Commented Sep 14, 2011 at 14:16
  • 1
    @Pankja Actually, they took the interface idea from Java (like a good part of C#'s features). Commented Sep 14, 2011 at 17:01
3

Use of interfaces helps a system stay decoupled and thus easier to refactor, change, and redeploy. It is a very core concept to object-oriented orthodoxy and I first learned about it when C++ gurus made "pure abstract classes" which are quite equivalent to interfaces.

1
  • Decoupling is important because it keeps different components of a system independent of each other. That even large-impact changes in one component don't ripple out to other components. Think of power plugs as an interface to your utility company (specifying voltage and the physical pins and format of the plug). Thanks to this interface, the utility can completely change the way they produce power (e.g. use solar technology), yet none of the devices will even notice let alone change.
    – miraculixx
    Commented Dec 1, 2012 at 14:25
2

They are mostly used for code reusability. If you code to the interface you can use a diffrent class that inherits from that interface and not break everything.

Also they are very usefull in webservices where you want to let the client know what a class does (so they can consume it) but dont want to give them the actual code.

2

A real world implementation:

You can cast an object as the Interface type:

IHelper h = (IHelper)o;
h.HelperMethod();

You can create a list of an interface

List<IHelper> HelperList = new List<IHelper>();

With these objects you can access any of the interface methods or properties. In this manner you can define an interface for your part of a program. And build the logic around it. Then someone else can implement your interface in their Business objects. If the BO's change they can change the logic for the interface components and not require a change to the logic for your piece.

2

As a young programmer/developer, just learning C# you might not see the usefulness of interface, because you might write your codes using your classes and the code works fine, but in real life scenario, building a scalable, robust and maintainable application involves using some architectural and patterns, which can only be made possible by using interface, example is in dependency injection.

0

Interfaces lend to plugin-style modularity by providing a mechanism for classes to understand (and subscribe to) certain kinds of messages that your system delivers. I'll elaborate.

In your application, you decide that whenever a form is loaded or reloaded you want all of the things it hosts to be cleared. You define an IClear interface which implements Clear. Additionally, you decide that whenever the user hits the save button that the form should attempt to persist its state. Thus, everything that abides by ISave receives a message to persist its state. Of course, practically speaking, most interfaces handle several messages.

What sets interfaces apart is that common behavior can be achieved without inheritance. The class that implement a given interface simply understands how to behave when issued a command (a command message) or how to respond when queried (a query message). Essentially, the classes in your application understand the messages your application provides. This makes it easier to construct a modular system into which things can be plugged.

In most languages there are mechanisms (like LINQ) for querying things that abide by an interface. This will usually help you eliminate conditional logic because you won't have to tell dissimilar things (that are not necessary derived of the same inheritance chain) how to behave similarly (according to a particular message). Instead, you gather everything that understands a certain message (abides by an interface) and publish the message.

For example, you could replace...

Me.PublishDate.Clear()
Me.Subject.Clear()
Me.Body.Clear()

...with:

For Each ctl As IClear In Me.Controls.OfType(Of IClear)()
    ctl.Clear()
Next

Which effectively sounds a lot like:

Hear ye, Hear ye! Would everyone who understands clearing, please Clear now!

In this way, we can programmatically avoid telling each and every thing to clear itself. And when clearable items are added in the future they simply respond without any additional code.

0

The following is pseudocode:

class MyClass{

    private MyInterface = new MyInterfaceImplementationB();

    // Code using Thingy 

}

interface MyInterface{

    myMethod();

}

class MyInterfaceImplementationA{ myMethod(){ // method implementation A } }

class MyInterfaceImplementationB{ myMethod(){ // method implementation B } }

class MyInterfaceImplementationC{ myMethod(){ // method implementation C } }

The last classes can be completely different implementations.

Unless multiple inheritance is possible, inheritance imposes the implementation of the parent class making things more rigid. Programming against interfaces on the other hand can allow your code or a framework to be extremely flexible. If you ever come accross a case where you wished you could swap around classes in an inheritance chain you'll understand why.

For example, a framework that provides a Reader originally intended to read data from disk could be re-implemented to do something of the same nature but in a totally different way. Like interpret Morse code for example.

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