Sunday, June 2, 2013

Accessing Methods of Explicit Interfaces

We have seen on how to implement more than one interface which have methods/properties with the same name and signature using explicit interfaces. Now how do we create instance of the class and call these methods individually.

The following example contains 2 interfaces IEmployee and IDepartment, both the interfaces contain a method GetName() with the same name and signature. The class OfficeClass implements both the interfaces and implements the GetName method from both the interfaces using Explicit Interface Implementation.
    interface IEmployee
    {
        string GetName();
    }
    //
    interface IDepartment
    {
        string GetName();
    }
    //
    class OfficeClass : IEmployee, IDepartment
    {
        string IEmployee.GetName()
        {
            return "test employee";
        }
        //
        string IDepartment.GetName()
        {
            return "test department";
        }
    }

Now let us create an instance of the Office class and call the GetName() methods defined in both the interfaces individually.

    OfficeClass objOfficeClass = new OfficeClass();
    IEmployee objIEmployee = (IEmployee)objOfficeClass;
    IDepartment objIDepartment = (IDepartment)objOfficeClass;
    //
    Console.WriteLine("Call From objIEmployee: " + objIEmployee.GetName());
    Console.WriteLine("Call From objIDepartment: " + objIDepartment.GetName());

The output will be as follows

Call From objIEmployee: test employee
Call From objIDepartment: test department

In case of explicit interfaces we should not try to call the methods directly using the object of the class, trying so will lead to a compiler error as follows.

Console.WriteLine("Call From objOfficeClass : " + objOfficeClass.GetName());


Error:
OfficeClass does not contain a definition for 'GetName' and no extension method 'GetName' accepting a first argument of type 'OfficeClass'

Search Flipkart Products:
Flipkart.com

No comments: