Click here to Skip to main content
Click here to Skip to main content

What’s the Deal with Interfaces?

By , 19 Apr 2010
 

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:

public interface IRandomNumberGen
{
    int GetNextNumber(); // note: public is not needed
}

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 private method 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.

class RandomNumberCoinFlip : IRandomNumberGen
{
    public int GetNextNumber()
    {
        // flip a coin for each bit of the number
        return 1;
    }
    private String CoinType; // penny, nickel, etc.
}

class RandomNumberOuija  : IRandomNumberGen
{
    public int GetNextNumber()
    {
        // Use a Ouija board to get a number
        return 2;
    }
}

Notes

Both classes implement the GetNextNumber() function. One class has an additional field…but that's OK; it doesn't matter:

As long as a class implements the functions in the Interface, it can do anything else it pleases. But a class derived from an Interface must implement the functions in the Interface.

So big deal, what have we accomplished?

Here are the Classes in Use

protected void Button1_Click(object sender, EventArgs e)
{
    IRandomNumberGen Generator;

    Generator = new RandomNumberCoinFlip();
    Response.Write(Generator.GetNextNumber() + "<br />");

    Generator = new RandomNumberOuija();
    Response.Write(Generator.GetNextNumber() + "<br />");
}

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.

Here’s Another Usage Example

public void MakeAMove(IRandomNumberGen NumberGenerator)
{
    int Number = NumberGenerator.GetNextNumber();
    // do something with Random Number
}

protected void Button1_Click(object sender, EventArgs e)
{
    MakeAMove(new RandomNumberCoinFlip());
    MakeAMove(new RandomNumberOuija());
}

Notes

This shows a function that takes an Interface as a parameter. Any object derived from the Interface can be passed to the function.

That's cool but the same thing could be accomplished with an abstract base class and virtual functions. So what's the deal with Interfaces?

Multiple-Inheritance is not Supported in .NET… Except for Interfaces!

Here is one more class that implements the Interface. In addition to IRandomNumberGen, it implements IDisposable.

class RandomNumberDeckOfCards :  IRandomNumberGen, IDisposable
{
    public int GetNextNumber()
    {
        // Shuffle deck, pick a card
        return 3;
    }
    public void Dispose()
    {
        // free up deck
    }
}

And here it is being used:

protected void Button1_Click(object sender, EventArgs e)
{
    IRandomNumberGen Generator;

    Generator = new RandomNumberDeckOfCards();
    Response.Write(Generator.GetNextNumber() + "<br />");

    IDisposable Disposer = Generator as IDisposable;
    Disposer.Dispose();
}

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 abstract classes and interfaces. In addition to "multiple inheritance" which abstract classes 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.

public interface MyInterface
{
    int LastResult { get; set; }
}

public class MyClass : MyInterface
{
    public int LastResult { get; set; }
}

Steve Wellens

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Steve Wellens
EndWell Software, Inc.
United States United States
I am an independent contractor/consultant working in the Twin Cities area in Minnesota. I work in .Net, Asp.Net, C#, C++, XML, SQL, Windows Forms, HTML, CSS, etc., etc., etc.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membernikhil _singh12-Sep-12 0:50 
This Article is really awesome.A totally different Approach to understand Better.
GeneralMy vote of 4memberAlluvialDeposit19-Jul-12 8:59 
Nice beginners article Smile | :)
GeneralMy vote of 5membernikhil _singh6-May-12 23:02 
really amazing Article to understand interface.
GeneralMy vote of 5memberjim lahey22-Mar-12 5:51 
Clear and concise, my 5!
GeneralMy vote of 5memberdasunnavoda29-Jan-12 16:14 
I have read so many articles about Interfaces. But this one better than everything.
GeneralMy vote of 4memberSChristmas12-Jul-11 1:26 
good
GeneralQuestion for other developers about interfacesmemberMember 321295226-Apr-10 23:37 
Why is it that sofar i never got to write an interface
as a developer ?
 
Writing them usually comes with a role that is
more software-design oriented maybe ?
GeneralRe: Question for other developers about interfacesmemberSteve Wellens27-Apr-10 2:36 
Maybe you never needed to write an interface.
 
A golfer doesn't always use every club in his bag.
A carpenter doesn't always use every tool in his toolbox.
A developer doesn't always use every feature available in his language.
Steve Wellens

GeneralRe: Question for other developers about interfacesmemberZeEv 127-Apr-10 20:44 
Thanks for the intriguing metaphores Smile | :) !
 
Point well taken...
GeneralThe way I understand Interfacesmemberchuckdawit26-Apr-10 19:06 
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!
GeneralRe: The way I understand InterfacesmemberSteve Wellens27-Apr-10 2:34 
An Interface can be viewed as a contract as you described.
 
By using interfaces, "plug in modules" are much more likely to be able to be swapped in and out easily.
 
Here's all the interfaces a SortedList implements:
 
public class SortedList : IDictionary, ICollection, IEnumerable, ICloneable
Steve Wellens

GeneralAs a begginer, I liked itmemberQubeIt26-Apr-10 16:15 
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".
 
This article has reinforced what I've learned. Thank you.
 
-Brian Hall-
Generalinherit an interface..memberAndrei Rinea23-Apr-10 0:08 
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.

GeneralRe: inherit an interface..memberSteve Wellens23-Apr-10 1:58 
I think the terminology is OK.
 
Here's some of Microsoft's latest documentation:
 
"When a class or struct is said to inherit an interface, it means that the class or struct provides an implementation for all of the members defined by the interface."
 
http://msdn.microsoft.com/en-us/library/ms173156.aspx[^]
 
If you can convince Microsoft to change their language, I will conform since they are the creators/owners of C#.
Steve Wellens

GeneralWish you added some morememberlarry11820-Apr-10 11:23 
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.
 
Larry
 
Such a Larry
Generalpropertiesmemberwallism19-Apr-10 12:47 
Hey good article overall, it's an easy read and will no doubt 'fit someones brain'.
 
One thing though, you say at the bottom "If you need fields or properties in the base class, you cannot use interfaces.". Yes you cannot have fields but you CAN have properties.
 
For example:
int LastResult{get;set;}
would be quite valid to have on your sample interface.
 
Just like a method, implementors of the interface must implement their own version of the property.
GeneralRe: propertiesmemberSteve Wellens19-Apr-10 14:47 
Wow, thanks for pointing that out. I tried it and it works although it somehow seems wrong Smile | :)
 
public interface MyInterface
{
    int LastResult { get; set; }
}
 
public class MyClass : MyInterface
{
    public int LastResult { get; set; }
}
 
Now I have to update the article Frown | :(
Steve Wellens

Generala "touchy" subject.memberDiamonddrake13-Apr-10 12:37 
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.
GeneralRe: a "touchy" subject.memberSteve Wellens13-Apr-10 12:48 
It shouldn't be touchy. We are all engineers (hopefully).
 
I don't blame people for skimming over stuff: We all have to do it to some extent because there is SO much information and SO little time and we DO have to get the job done.
 
Thanks for your comment.
Steve Wellens

GeneralMy vote of 1memberRoms4-Feb-10 6:31 
Does not make the point, as stated in the title of the article.
GeneralRe: My vote of 1memberjim lahey22-Mar-12 5:50 
No, you just don't get interfaces. The usage examples are clear enough.
GeneralIt fits my brainmemberbaiyuxiong9-Dec-09 2:59 
Such a good article
Thanks
GeneralRe: It fits my brainmemberWesMcGJr20-Apr-10 4:13 
Mine too. Smile | :)
GeneralRe: It fits my brainmemberHezek1ah27-Apr-10 5:46 
Mine too. Smile | :)
GeneralCould help some...memberCurtainDog21-Jul-09 2:37 
I like your "fits the brain" rationale. I wouldn't go so far as to call it trivial, but understanding can indeed come as a flash of inspiration.
 
Regarding the specific example presented here I would say that randomness is an implementation detail and doesn't belong in an interface Smile | :)
GeneralNothing said...memberPaul Selormey18-Jul-09 3:21 
There is nothing special in this article for a beginner. I think the most important thing is knowing when to make a choice between interface and abstract class. This is where most are confused.
Your sample codes could be done with abstract base class. So, what really have you explained to the beginner?
 
Also, try to take a little care when addressing beginners, you should show some good practice:
    IDisposable Disposer = Generator as IDisposable;
    Disposer.Dispose();
At least you should have checked whether Disposer is not null before using it.
 
Best regards,
Paul.
 

Jesus Christ is LOVE! Please tell somebody.

GeneralRe: Nothing said...memberWillemToerien19-Jul-09 21:49 
Also, I think it would be a good idea to show the beginners where to use the interface in designs for a solution and how to implement them as well for abstract classes.
 

public interface IEmployee
{
int IdEmployee { get; set; }
string Name { get; set; }
}
 
public interface IDataHandler
{
void Create(IEmployee employee);
object DataSource { get; set; }
}
 
public abstract class DataHandler : IDataHandler
{
protected DataHandler(object dataSource = null)
{
DataSource = dataSource;
}
 
public abstract void Create(IEmployee employee);
 
public object DataSource { get; set; }
}

 
If we take this for example, the user can use any object and send it to the data handler, as long as it inherits from IEmployee. And the data handler can do anything to the object, save it to Xml, Sql, Access, etc. As long as it inherits DataHandler.
 
Assumption is the mother of all f*ck ups.

GeneralRe: Nothing said...membersupercat912-Apr-10 8:42 
Paul Selormey wrote:
Your sample codes could be done with abstract base class. So, what really have you explained to the beginner?

 
The article does point out that multiple inheritance is allowed for interfaces but not base classes, which is the main reason that interfaces are ever preferable to base classes. One could, for example, have an iRandomNumberGen which was derived from UserControl and provided a UI to adjust the random number generation. If an abstract RandomNumberGen class had been used instead of an interface, that would have been more difficult.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 19 Apr 2010
Article Copyright 2009 by Steve Wellens
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid