Monday, August 26, 2013

Calling explicitly implemented interface methods from other instance methods in C#

In one of my previous post related to interface usage, I had asked to explicitly implement interfaces always to achieve the principle of "Program to interface not to implementation". If we follow the advise you may enter into scenarios where you need to call an explicitly implemented method from another method. Another method can be interface method or normal method. Below is the situation.


    public interface IMyInterface
    {
        void Foo();
        void Foo(string value);
    }
    public class MyClass : IMyInterface
    {
        void IMyInterface.Foo()
        {
            Console.WriteLine("Value is {0}""Default Value");
        }
        void IMyInterface.Foo(string value)
        {
            Console.WriteLine("Value is {0}",value);
        }
    }


In this scenario its good to call the second Foo method (parameterized) from the first one. But if you try to simply call it, you will end up in compilation error. Also you cannot do it using this keyword even though the method resides in same class. So what should we do? 

If you really studied the theory behind the explicit interface implementation before coming into the programing field, you would have known this scenario. But still there are people who needs google to tackle this situation. The solution is to cast this object to IMyInterface and call the method. Below is the code.


    public class MyClass : IMyInterface
    {
        void IMyInterface.Foo()
        {
            (this as IMyInterface).Foo("Default Value");
        }
        void IMyInterface.Foo(string value)
        {
            Console.WriteLine("Value is {0}",value);
        }
    }

Happy coding...

No comments: