Below is my code:
public interface I1
{
void method1();
}
public interface I2
{
void method1();
}
class MyClass
{
static void Main(string[] args)
{
One one = new One();
}
}
public class One :I1,I2
{
void I1.method1()
{
Console.WriteLine("This is method1 from Interface 1");
}
void I2.method1()
{
Console.WriteLine("This is method1 from Interface 2");
}
}
I have below issues:
You have explicit interface implementations. Therefore you can only access your methods by casting to your instance to interface type
One one = new One();
I1 x = (I1)one;
x.method1();
I am unable to declare methods as Public in class One as these are Interface methods.
That's only because you're using explicit interface implementation. Assuming you really need the two different implementations, you could make one of them implicit:
public void method1()
{
Console.WriteLine("This is method1 from Interface 1");
}
void I2.method1()
{
Console.WriteLine("This is method1 from Interface 2");
}
Note how now we can specify the public
access modifier, and one.method1()
will call that public method. Explicit interface implementation only allows access to the method via an expression whose compile-time type is the interface (rather than the class implementing it).
I am unable to call these Interface method implementations from MyClass instance in the Main function.
Again, only because you're using explicit interface implementation and your one
variable is of type One
.
Basically you can call the methods with:
One one = new One();
I1 i1 = one;
I2 i2 = one;
i1.method1();
i2.method1();
Or just cast:
((I1)one).method1();
((I2)one).method1();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With