Banner Ad

Sunday, June 1, 2014

Daily interview Question #10 : what is the purpose of "explicit" implementation of interface?

By Francis   Posted at   7:32 AM   CodeProject No comments

There are 2 purposes of explicit implementation of Interface:
First, it is used to avoid name collision between interface methods. That is if you are going to create a class library, there may be a chance to use the same name in several places. At that time "explicit" implementation comes as a rescue.
Secondly, You cannot access that implemented method through the object of the class directly. Instead you typecast it as Interface reference then you can access it. This is because, the C# complier, unable to determine which one the user want to call.

                   In another way, you need to add "public" access specifier in the interface's implemented method in a class. But if you "explicitly" implemented the interface you can change this one.That means, it will be look alike private method. But with one exception, you can access that explicit implemented method through the reference of the interface. Please take a look at the below code for a detailed explanation.

    
    interface ISample
    {
        void method1();
        void method2();
    }
    interface IAnotherSample
    {
        void method1();
    }
    class A : ISample, IAnotherSample
    {
        // Explicit implementation avoid name collision
        void ISample.method1()
        {

        }
        void IAnotherSample.method1()
        {
        }
        // Implicit implementation
        public void method2()
        {

        }

    }
    // Inherit Class A
    class B : A
    {
        // Create Object for class A
        A obj = new A();
        B()
        {
            // You can call method2
            obj.method2();
            // Error: You cannot call method1 Since Explicit implementation
            //obj.method1();
            // But you can access it by Interface Reference
            ((ISample)obj).method1();
        }
    }

Finally, one more point, explicitly implemented interfaces' methods are not listed down in the Visual Studio IDE's intellisense.
Lose of Intellisense

Readers do you have any thoughts. Please comment it!!



About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us