18 March 2009 HowTo, Interfaces Robert Muehsig

image Interfaces are an important feature for designing great software, but many programming newbies have a understanding problem - Why should I use "interfaces"? What is an "interface"?

A very simple sample
I would like to create 3 types (Train, Car, Human) in my (very simple, not real world) sample. Each type is movable and that´s why I want to create the "IMovable" interface. 
To move these types I implement a  "God" class which can move these objects as he wishes. (I know - it´s a very real sample ;) ).

Structur:

image

The most important thing is our "IMovable" interfaces (the name of an interface begins with "I" in .NET):

    public interface IMovable
    {
        void Move();
    }

You define methods, properties or events in the interface - it´s a kind of a contract and the real implementation doesn´t matter.

    public class Human : IMovable
    {
        #region IMovable Member

        public void Move()
        {
            Console.WriteLine("The human take a step.");
        }

        #endregion
    }

Our human implements the interface - and "take a step" to "Move". The signature of the methods must be equal to the method of the interface (parameters, return value)!

Implementing god
Now it´s time to move! We implement now our God class with the "MoveObject" method. It takes an item which implement the "IMovable" interface:

    public class God
    {
        public static void MoveObject(IMovable item)
        {
            Console.WriteLine("God moves something...");
            item.Move();
        }
    }

The method "MoveObject" takes anything that implements the interface - the concret type doesn´t matter! You can now put a car, train, human or another type in it - as long as it implements the "IMovable" interface!

image

Now we can create many classes which implement the interface and we don´t need to change anything in our God class!

Our test program:

    class Program
    {
        static void Main(string[] args)
        {
            Car BMW = new Car();
            Train ICE = new Train();
            Human Robert = new Human();

            God.MoveObject(BMW);
            God.MoveObject(ICE);
            God.MoveObject(Robert);

            Console.ReadLine();
        }
    }

We have a train, a BMW and me - the result (the original source code was in german, I just translated it in this post) :

image

[ Download Source Code ]


Written by Robert Muehsig

Software Developer - from Saxony, Germany - working on primedocs.io. Microsoft MVP & Web Geek.
Other Projects: KnowYourStack.com | ExpensiveMeeting | EinKofferVollerReisen.de