Tagged as

What’s the Deal with Interfaces?

Many beginners struggle with the concept of an Interface. Over on the ASP.NET forums, where I moderate, the question is asked a surprising number of times. I'm going to try to describe and explain the concept of an Interface…simply and concisely.

This post is for beginners.

Many beginners struggle with the concept of an Interface. Over on the ASP.NET forums, where I moderate, the question is asked a surprising number of times. I'm going to try to describe and explain the concept of an Interface…simply and concisely.

Let's say we are going to program a game and the game needs a random number generator.

We want to try different random number generators because all random number generators are not created equal. To make it easy to switch number generators, we will use an Interface.

The Interface

So, here is the (simple as possible) Interface for our Random Number Generator:

Notes

The public keyword is not needed (or even allowed) on the GetNextNumber() method. An interface declares access methods so by default they must be public. A privatemethod in an interface makes no sense...and causes an error.

An Interface cannot contain fields. Doing so causes an error.

Hmmm, it seems an Interface is a collection of empty functions that are implicitly public.

Derive some Classes from the Interface

Here are two Random Number Generators each inheriting from our Interface.

Notes

The Generator reference can be assigned to any object created from a class derived from the IRandomNumberGen Interface and it can call the GetNextNumber() method. It doesn't know or care about any part of the class except the methods it expects to be there.

Notes

As before, an IRandomNumberGen reference can be assigned to the object and the GetNextNumber() method called.

In addition, an IDisposable reference can be assigned (with a cast) to the object since it implements IDisposable and the Dispose() method can be called.

In the above code, the two Interface references, Generator and Disposer, both point to the same object. They have different 'views' of the same object. And that, is the deal with interfaces.

Finale

I know there are thousands of articles around explaining this concept which is odd because once understood, the concept is trivial. But sometimes one explanation "fits the brain" better than another explanation. I hope this explanation fits someone's brain.

Update

Many have asked for clarification between abstractclasses and interfaces. In addition to "multiple inheritance" which abstractclasses do not support, there is another key difference: Interface classes may NOT contain fields. If you need fields or properties in the base class, you cannot use interfaces.

Update 2

Strike part of the last update. You can have properties in an interface but not fields. Thanks to Wallism for pointing this out.

Please someone correct me if I'm wrong because I'm learning how to use Interfaces right now.
Tne way I understand Interfaces is through the relationship between client and server.
Ex. If I write a class and declare an interface with two methods in it like so:

Interface IMyInterface
{
int getTime();
int setTime();
}

public class MyClass
{

int getTime()
{
//do some stuff
return 1;
}

int setTime()
{
//do some stuff
return 1;
}
}

Now I pass this class as a .dll to a client for him to use.
He has my .dll with my class 'MyClass' and he decides that he wants to use both methods (setTime() and getTime()) in his code. That's fine!
Ex.
using mydll.dll
namespace somenamespace {
public class MyClientClass
{
IMyInterface testInterface = new MyClass();
int retval1 = testInterface.setTime();
int retval2 = testInterface.getTime();
}
}

NOW, say in one week I decide I want to change my code (.dll) and remove the setTime() method. Oops! My client is using it and if I remove it then his code will break if I send him the .dll with the removed (setTime()) method. Remember he's using both methods from my .dll. So to insure that I don't break my clients code, I create an interface that insures I have/use certain methods.

That's my understanding so far, please correct me if incorrect or add more detail if correct to some degree.
Thanks!

I've been learning development via the C# language for about 7 months now. I learned about interfaces about 4 months into it. Conceptually I somewhat understood it, and I could recite the technical explanations back almost word for word. The problem I had was using them to solve a programming problem. Mainly in terms of architecture. About 6 months into my learning experience, I started learning about MVC (Model-View-Controller) and MVP (Model-View-Presenter) and that's when I forced myself to grasp the *why* to use interfaces. As "they" say in motivational speaking, "Once you find the 'why', the how will figure itself out".

Please stop saying "inherit an interface" or multiple inheritance allowed for interfaces. You don't inherit an interface unless you are another interface. If you are a class or a struct you implement it.

I find these examples so frustrating because the world does not consist of integers. I just posted a question on this same subject but my issues have to deal with passing decimals, dates and booleans and how to handle null's.

I am so frustrated by the lack of documentation on anything but strings an integers.

Sorry just need to vent I'm down to 50 cents an hour on a project I should have had completed a week ago.

This is kind of a touchy subject as one could infer from the different types of comments. I personally think its a good blog. You show how to use it, what its used for, and what makes it useful. It's a shame that so many new C# programmers skip over learning this as its a powerful tool when programming in a group setting.