Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
44  
"If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them." This statement makes me suspect you should look a bit more into the advantages of statically typed languages. –  Steven Jeuris Sep 14 '11 at 14:23
28  
Forget C#, forget Java, forget the language. It's simply thinking in terms of OO. I would encourage you to pick up some reading material from folks like Robert C. Martin, Martin Fowler, Michael Feathers, the Gang of Four, etc., as it will help expand your thinking. –  Anthony Pegram Sep 14 '11 at 15:09
20  
It took me more than two years to really understand what interfaces are good for. My suggestion: study Design Patterns. As most of them rely on interfaces, you will quickly understand why they are so useful. –  Oliver Weiler Sep 14 '11 at 17:00
27  
You've got a lot to learn friend. –  ChaosPandion Sep 14 '11 at 18:52
39  
@ChaosPandion we've all got a lot to learn –  qntmfred Sep 14 '11 at 19:04

19 Answers 19

up vote 97 down vote accepted

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.

share|improve this answer
16  
@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.) –  Eric Lippert Sep 14 '11 at 17:23
1  
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. –  configurator Sep 14 '11 at 17:27
6  
+1 for "Well I'm glad you like it." And all the other stuff too. –  Robert S. Sep 15 '11 at 16:33

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.

share|improve this answer

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.

share|improve this answer
3  
The bottom left object doesn't look like it implements IPowerPlug =) –  WeekendWarrior Sep 20 '11 at 20:21
50  
Damn, but we'll have to use an Adapter pattern in order to use the IPowerPlug in different countries! –  Steven Jeuris Sep 20 '11 at 22:17
3  
@WeekendWarrior - I'd love to know how it boils water without one. –  Slomojo Sep 21 '11 at 2:55
5  
@Aditya ... and now I breathe a heavy sigh. We can also find many kettles still available that don't use a power-plug... HOWEVER, the one illustrated would be up dookie creek without the proverbial paddle, wouldn't it. Top marks for being a smart guy ;) ... I'm going to assume you get the point of the illustration though, and it's nice that it's still getting seen. –  Slomojo Apr 5 '12 at 5:46
3  
@Aditya Electricity was discovered, not invented. –  lesderid Jan 29 '13 at 21:56

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.

share|improve this answer
1  
Never heard of polymorphy, you mean polymorphism? –  Steven Jeuris Sep 14 '11 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 –  Pankaj Upadhyay Sep 14 '11 at 14:15
8  
@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 Sep 14 '11 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 –  Pankaj Upadhyay Sep 14 '11 at 14:25
8  
@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. –  Jonathan Henson Sep 14 '11 at 14:33

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.

share|improve this answer
2  
+1 for test isolation. –  StuperUser Sep 14 '11 at 14:46
1  
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 Sep 15 '11 at 5:17

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.

share|improve this answer
5  
Actually, foreach does not require IEnumerable: msdn.microsoft.com/en-us/library/9yb8xew9%28VS.80%29.aspx –  Matt H Sep 14 '11 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. –  Pankaj Upadhyay Sep 14 '11 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 Sep 14 '11 at 14:53
3  
@Iceman. LOL....I am from india. And here it is a common idiom which reflects doing easy things the difficult way. –  Pankaj Upadhyay Sep 14 '11 at 17:34

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.

share|improve this answer

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?

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer
1  
Very well put! I'm guessing you'll like my article on abstract classes. Abstraction is everything. –  Steven Jeuris Sep 14 '11 at 14:33

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.
share|improve this answer
1  
+1 to multiple inheritance usefulness. –  Jonathan Henson Sep 14 '11 at 14:16
1  
@Pankja Actually, they took the interface idea from Java (like a good part of C#'s features). –  Oliver Weiler Sep 14 '11 at 17:01

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

The following is pseudocode:

class MyClass{

    private MyInterface = new ThingyImplementationB();

    // 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.

share|improve this answer

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.

share|improve this answer

protected by MichaelT Jun 6 at 2:10

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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