Search This Blog

Friday, 20 July 2012

Interfaces


First and foremost, interfaces in C# are a means to get around the lack of multiple inheritance in C#, meaning you cannot inherit from multiple classes but you can implement multiple interfaces. OOP tries to resemble how objects are defined in the real life, and interfaces are a very logical way of grouping objects in terms of behavior.


An interface is a contract between itself and any class that implements it. This contract states that any class that implements the interface will implement the interface's properties, methods and/or events. An interface contains no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers & events.

Example:

    class Program
    {
        public static void Main()
        {
            Class1 Cls = new Class1();
            Cls.DoStuff();
            Cls.DoMoreStuff();
            Console.ReadLine();
        }
    }

    interface Interface1
    {
        void DoStuff();
    }
    interface Interface2
    {
        void DoMoreStuff();
    }
    class Class1:Interface1, Interface2
    {

        #region Interface1 Members

        public void DoStuff()
        {
            Console.WriteLine("Do Stuff");
        }

        #endregion

        #region Interface2 Members

        public void DoMoreStuff()
        {
            Console.WriteLine("Do More Stuff");
        }

        #endregion
    }



Why use Interface?

Consider the concept of data hiding. Let's say you want to provide a class to some client code, but don't want to give them full access. One way to restrict access without limiting the functionality of your class is to implement an interface and require the client code to get objects through a factory:
using System;

     public class Program {
            static void Main() {
                    IFoo myfoo = FooFactory.GetFoo();
                    Bar mybar = new Bar();

                    myfoo.Print();
                    mybar.Print();
                    mybar.Test();
            }
     }

     // Restricted type for clients
     public interface IFoo {
            void Print();
     }

     // Factory for clients
     public class FooFactory {
            public static IFoo GetFoo() {
                    return new Bar();
            }
     }

  // Fully functional type for us
     internal class Bar: IFoo {
            public void Print() {
                    Console.WriteLine( "Foo!" );
            }

            public void Test() {
                    Console.WriteLine( "Test" );
            }
     }


Difference between regular classes, abstract classes and interfaces

  • Interface: contract only, no implementation, no instantiation
  • Abstract class: contract, some implementation, no instantiation
  • Class: contract, implementation, instantiation




No comments:

Post a Comment