Programming Interfaces in C#

What is an Interface? An interface is a encapsulator, for lack of a better term (Its 2:30 am). It contains the signatures of methods, events or delegates. The best way for me explain a good use for an interface is through example.

Say, you have a superclass that describes your object. This superclass contains properties that from it, all inherited classes will possess. Now say some of these properties or behaviors that every single inherited class will have to override because it needs to be slightly different. Enter the interface. Assume you have a finite array of behaviors that any of these inherited classes will need to override to. An interface can be used to implement these behaviors.

So what does an Interface look like? Let me demonstrate using the hello world scenario.

interface IHelloWorld

     {

     string HelloWorld();

     }

You notice, that I apprear to be simply declaring the HelloWorld() method. That is because an Interface is a skeleton of a the class(es) that will implement it. Now say that in program, we know that we will need to get a string “Hello World” in all caps and all lower cases. But of course, we also want to ensure that we can accomodate additional requirements that may come along in the future. we could then write the following to classes to implement this interface.

class HelloWorldCAPS : IHelloWorld

    {

        public string HelloWorld()

        {

            return "HELLO WORLD!";

        }

    }

class HelloWorldLOWER : IHelloWorld

    {

        public string HelloWorld()

        {

            return "hello world!";

        }

    }

Each of the above classes “implements” our interface. Now, through the use of a single interface, we can instaciate an object that will perform one of two behaviors.

To actually instaciate an object we simply perform the following:

            IHelloWorld Message = new HelloWorldCAPS();

            Console.WriteLine(Message.HelloWorld());

– or –

            IHelloWorld Message = new HelloWorldLOWER();

            Console.WriteLine(Message.HelloWorld());

Notice that when instanciating the object, we decide which class to implement. In the future, you may need to create additional behaviors, or in this case, print “Hello World” differently. You can simply create a new class from which to implement your IHelloWorld interface and you’re on your way. This is a good alternative to straight up inheriting from and overriding methods of a superclass.

  • So, what he have to learn from this is, only build into your base class or superclass methods that will persist accross all inherited classes.
  • Use an interface to encapsulate code that will vary amongst your inherited classes.
  • Using interfaces is a good way to build easily maintainable code as it allows you to add new functionality without affecting the need for reworking loads of code.