Sunday, June 2, 2013

What are Interfaces?

An Interface defines a set of methods and properties which should be implemented in the class which implements the interface. Interfaces help us in implementing the concept of multiple inheritances in C#. In C# a class cannot derive from more than one parent class, but can implement more than one interface, hence they help us in implementing multiple inheritance.

In the following example the Interface IEmployee defines 2 methods and the class EmployeeClass implements this interface and adds the method definition to both these methods declared in the interface.
    interface IEmployee
    {
        string GetEmployeeName();
        string GetEmployeeAddress();
    }
    //
    class EmployeeClass : IEmployee
    {
        public string GetEmployeeName()
        {
            return "test name";
        }
        //
        public string GetEmployeeAddress()
        {
            return "test address";
        }
    }

It is mandatory for any class which implements an Interface to define the body of the methods and functions declared in the interface, failing will result in a compiler error.

In the following example the Interface IEmployee declared 2 methods but the class implementing the interface does not implement the methods hence leading to an error.

    interface IEmployee
    {
        string GetEmployeeName();
        string GetEmployeeAddress();
    }
    //
    class EmployeeClass : IEmployee
    {

    }

Error:
EmployeeClass does not implement interface member IEmployee.GetEmployeeName()
EmployeeClass does not implement interface member IEmployee.GetEmployeeAddress()

Search Flipkart Products:
Flipkart.com

No comments: