Steve Wellens

Programming in the .Net environment

Sponsors

Links

What’s the Deal with Interfaces?

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:

interface IRandomNumberGen
{
    int GetNextNumber();  
}

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, dime, 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 RandomNumberDeckOfCardsIRandomNumberGen, 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:

Correction: An interface does support properties:

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

 

Steve Wellens

Posted: Jul 17 2009, 07:15 PM by SGWellens | with 23 comment(s) |
Filed under: , ,

Comments

@BenAlabaster said:

Good article - though you don't really connect the dots for the beginner.  

Instantiating concrete objects as you have doesn't really give the full picture of the usefulness of interfaces.  I think as a beginner, I would miss the underlying purpose of interfaces from this explanation.

You've shown very concisely how to implement interfaces but don't really help the reader discover how they fit into the bigger picture and so leaves them somewhat short of being able to make good use of the [very good] information that you have provided.

I guess my critique is add some info that helps the reader to see the bigger picture - perhaps cover the basics of class factories and the factory pattern.

# July 17, 2009 11:41 PM

quachnguyen said:

It's a good article for novice, I usually get question about Interface in my interview.

I hope you will contribute some article about abstract class, virtual method.

Thanks,

NeonQuach

# July 19, 2009 5:22 AM

shanmugamm said:

Nice article and clear explanation.. Thanks

# July 20, 2009 2:48 PM

kamii47 said:

Nice Article

# July 22, 2009 1:00 AM

venkatesh mndya said:

usefull article

# July 23, 2009 1:01 AM

Zeeshan Umar said:

Nice article, agreed with quachnguyen , generally many people get confused that when to use interface and when to use abstract class.

# August 10, 2009 8:41 AM

Zeeshan Umar said:

Nice Article , thanks for sharing

# September 9, 2009 2:41 AM

Shiv said:

Finally an Article on interfaces which made sense..I was trying to understand the real use of interfaces for 2 years now.. It is only after reading you article that I have a fair idea of it

Thanks a ton

# November 17, 2009 6:12 PM

hajan said:

The first time I read about Interface was an example with programming a Game. This was very good example but Mr. Steve Wellens definitely provided even better and in-deep explained example which will definitely help beginners in understanding WHY INTERFACE? :)

Thank you for the input

# April 20, 2010 5:00 PM

Sam Marshall said:

You explained this very well and gave good code examples

Thanks

# May 24, 2010 9:00 PM

rajan said:

Nice explaination.thanks a lot

# June 7, 2010 10:38 AM

chickflickssuck said:

This article has helped me more than once.  It "Fit my brain" nicely the first time, and i came back to it *now* months later for help in actually using it! thanks!

# June 30, 2010 5:33 PM

Anooj said:

Thanks Steve,In a Way you explained Factory design Pattern as Well!!

# February 11, 2011 4:19 AM

Sivaraj said:

Wow..nice explanation with interface basics. Thank you so much.

# July 24, 2011 10:44 PM

rg said:

Wow... After couple years now I figured it out why and when to use interfaces,. The methods MakeAMove() and Button1_click explained me when to use interfaces.

Great...   Thank you

# November 4, 2011 12:01 AM

Kjell Liljegren, Sweden said:

Finally someone that not only showing the correct syntax for interface, but actually managed to show the WHY interface.

I've been looking for this info for many years now, sure not every day, I got a life too.

Excellent explained. don't pay any attention to the comment from BenAlabaster, he might be correct technically, but like so many already mentioned, Interface might be trivial when you understand it, but NEVER before that point.

Rgds, Kjell

# December 7, 2011 4:29 AM

Rookie said:

Could you please explain why do we need compare method in IComparable interface instead we can have our own method say CompareTwoObjects.

# January 22, 2012 12:09 AM

SGWellens said:

You should ask questions in the MSDN/asp.net/stackoverflow forums.

Because another object that is using the class is expecting a function with an exact signature (return type, number of arguments, type of arguments) so it can call it correctly.

# January 22, 2012 12:16 AM

Junior said:

I'm wondering why using the IEquatable interface if we have to implement it in the class knowing that just adding a method without using the interface would do the same thing?

# February 18, 2012 4:46 PM

SGWellens said:

I would guess that behind the scenes, the entry point of the function is tracked so when a user of the class uses it, the binding can take place immediately.

Otherwise the class would have to be searched for the correct function.

# February 18, 2012 6:15 PM

Hershey said:

Best article on interface.

# February 25, 2012 7:35 AM

Muhammad Tausif said:

Thanks, I was searching exactly that it here. Good effort...

# June 8, 2012 12:06 AM

sekar said:

Very good articale. Its helps lot

# September 27, 2012 12:32 PM