0

I came across very tricky situation about Implementing multiple interface having same Method name as Member.below is sample code for the problem.

public interface IBase1
{
    void show();
}
public interface IBase2
{
    void show();
}
public class BaseClass :IBase1, IBase2
{
    void IBase1.show()
    {
        Console.WriteLine("IBase1.show()");
    }
    void IBase2.show()
    {
        Console.WriteLine("IBase2.show()");
    }
}

Main Class

class Program
{
    static void Main(string[] args)
    {
        BaseClass obj = new BaseClass();
        //How to access IBase1.show() and IBase2.show()
    }

}

Here I have two interface's with member as show() method in each and one class which is implementing this two interface, now my question is how to access this method of BaseClass in Main function.

Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40

2 Answers2

5

You can cast to the appropriate interface

BaseClass obj = new BaseClass();
IBase1 b1 = (IBase1)obj;
b1.show(); // IBase1.show called
// or inline
((IBase1)obj).show();

Note, that you dont need to cast it, this should be fine

IBase1 b1 = obj;
b1.show(); // same as above

A nice side effect is that if you have a method where you specify the parameter type then it works fine too

public void ExecuteB1Show(IBase1 b1)
{
     b1.show();
}

ExecuteB1Show(obj); // no need to cast, obj is a IBase1
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 2
    Note that you don't actually need to cast explicitly - `IBase1 b1 = obj;` should be fine. All that's important is that you've got a reference of the right type. – Jon Skeet Sep 12 '16 at 08:49
  • @Jamiec and JonSkeet thanks, I know this was basic question but I stuck here lol, once again thanks for clearification – Jaydip Jadhav Sep 12 '16 at 08:56
1

Maybe it works with a cast:

((IBase1)obj).show();
((IBase2)obj).show();
Jules
  • 567
  • 1
  • 6
  • 15