user2203338
user2203338

Reputation:

Two interfaces with the same method

I have 2 interfaces

public interface I1
{
     void sayHello (); 
}

public interface I2 
{
     void sayHello (); 
}

// and my class that implements the two interfaces
public class C1: I1, I2
{
    void I1.sayHello () {}
    void I2.sayHello () {}
}

The problem is that I can not make them public or call them in another public method in C1

Upvotes: 1

Views: 169

Answers (2)

George Lica
George Lica

Reputation: 1816

You have to perform a typecast to whatever interface you want, even inside your class. If you want to call your I2 method implementation, call it using a cast like this:

(this as I2).SayHello();

Outside your class, for example you have to write:

C1 x = new C1();
(x as I1).SayHello();

What you have it is a so called explicit interface method implementation and those methods are accesible only through their interfaces.

Upvotes: 0

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

This is called explicitly implemented interface. Of course you can call those methods, but you have to retype your class instance to the correct interface first.

var c1 = new C1();
((I1)c1).sayHello();

Reference: https://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx

Upvotes: 3

Related Questions