Sunday 20 September 2015

Interface in C#

Key Points:
1.     An interface contains only the signatures of methods, properties, events or indexers.
2.     Interfaces cannot contain constructors.
3.     Interfaces cannot contain fields.
4.     By default Interfaces are internal we can make it public ,but not private, protected, or protected internal.
5.     The modifier are not valid for this items inside the Interface ,by default all items have "public" as modifier.
6.     Interface can be implement by other Interface but not by Other class,
     Ex:interface IDoctor: ITeach
7.     The class which implements interface, should implement all members of the Interface, else it results in compilation error.
8.     Interfaces cannot be initialized directly, since they do not have a definition for members, they should be implemented by either a class or structure. 

Why Interfaces...?
      The OOPS is gifted with a concept called Inheritance, but Inheritance has some limitations, like multiple inheritance we can’t able to create a derived class from two base classes, since it confuses the compiler.

      We will discuss it briefly with following example
class IndianFather
    {
        void setColour()
        {
            Console.WriteLine("Setting the Indian Colour");
        }
    }
    class ForeignFather
    {
        void setColour()
        {
            Console.WriteLine("Setting the Foreign Colour");
        }
    }
    class Child:IndianFather,ForeignFather
    {

    }

      From above example we can clearly know that, a derived class cannot have multiple base classes, so we can put the method setColour() into a interface
as follows
namespace InterfaceDemo
{
    interface IColour
    {
        void setColour();
    }
}

    Now we can implement IColour interface in two different classes IndianChild and ForeignChild
class IndianChild:IndianFather,IColour
    {
        public void setColour()
        {
            Console.WriteLine("Setting the Indian Colour");
        }
    }

    class ForeignChild : ForeignFather, IColour
    {
        public void setColour()
        {
            Console.WriteLine("Setting the Foreign Colour");
        }
    }

     Suppose we have same method  names in two different Interfaces, then we implement such methods with Interface name as prefix like
void IColour.setColour(), this kind of implementation is called as Explicit Implementation.
    
     We are not provided with option like Explicit Inheritance, so interfaces comes into picture.I n C# multiple inheritance is not allowed, Conversely it is achieved by interfaces like, a class can implement more than one interface.

I here explaining the real time example of Interfaces. Consider a hospital, which consists of various departments like Reception, Out Patient Department (OPD).

                               In reception department a guy who collects information from patients and get admission of the that patient, then he allocates the specific department to the patients viz OPD,Cardiology.

                             Now we create our first interface for the "Reception Department".
   namespace InterfaceDemo
  {
    interface IReception
    {
        void getAddmission();
        void allocateDepartment();
    }
}

                             Now we create our second interface for the "Treat Department".
namespace InterfaceDemo
{
    interface ITreat
    {
        void doOperation();
        void suggestPrecription();
    }
}
We will create a class called Hospital, which implements our Interfaces IReception and ITreat.

namespace InterfaceDemo
{
    class Hospital:IReception,ITreat
    {

        public void getAddmission()
        {
            Console.WriteLine("Getting addmission of patients");

        }

        public void allocateDepartment()
        {
            Console.WriteLine("Allocation department to patients");
        }

        public void doOperation()
        {
            Console.WriteLine("Doing operation to patients");
        }

        public void suggestPrecription()
        {
            Console.WriteLine("Suggesting prescription to patients");
        }
    }
}

                      If we instantiate our Hospital class then, we done with interfaces

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Hospital objHospital = new Hospital();
            objHospital .getAddmission();
            objHospital .allocateDepartment()
            objHospital .doOperation()
            objHospital .suggestPrecription()
        }
    }
}

                    Now this is the simple example of interfaces, but just imagine a real world scenario, where we want to instantiate a object for Reception Department, then if we follow the above steps, like

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Hospital objReceptionist = new Hospital();
            objReceptionist .getAddmission();
            objReceptionist .allocateDepartment();
            objReceptionist .doOperation();
            objReceptionist .suggestPrecription();
        }
    }
}

   The above code will provide all permissions for the receptionist viz getAddmission,allocateDepartment,doOperation,suggestPrecription. this will create a great disaster, since here receptionist  able to make operation as well as suggesting prescription. so we have to pull back receptionist to do only his work, the below code will do this work.

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            IReception objReceptionist = new Hospital();
            objReceptionist .getAddmission();
            objReceptionist .allocateDepartment();
        }
    }
}

Now on wards the Receptionist will do only his work. Great we successfully pulled him back, now we create a doctor to treat patients.

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            ITreat objDoctor = new Hospital();
            objDoctor.doOperation();
            objDoctor.suggestPrecription();
        }
    }
}

          Now we come across a use of Interfaces, now we look at one more vital essence of Interfaces.

As you all know about our first Interface IReception, it includes two implementation less methods like getAddmission(), allocateDepartment(), now we use same Interface IReception in our new class called College.

The college class implements one more Interface called ITeach, its declarations is as follows
namespace InterfaceDemo
{
    interface ITeach
    {
        void teachStudents();
        void conductExams();
    }
}

The class college implements IReception and ITeach as below
  class College : IReception,ITeach
    {

        public void getAddmission()
        {
            Console.WriteLine("Get Addmission in to College");
        }

        public void allocateDepartment()
        {
            Console.WriteLine("Allocation department for students");
        }

        public void teachStudents()
        {
            Console.WriteLine("Teach to students");
        }

        public void conductExams()
        {
            Console.WriteLine("Conducting Exams to students");
        }
    }

          In class College we implementing same methods of IReception with different implementation, depending on the context, since Interfaces keeps themselves open for different kind implementation on different context.

          Class College instantiate in same manner like Class Hospital
namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            College objCollege = new College();
            objCollege.getAddmission();
            objCollege.allocateDepartment();
            objCollege.teachStudents ();
            objCollege.conductExams ();
        }
    }
}


No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...