Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to call Interface methods from another class

Tags:

c#

oop

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:

  1. I am unable to declare methods as Public in class One as these are Interface methods.
  2. I am unable to call these Interface method implementations from MyClass instance in the Main function.
like image 577
RKh Avatar asked Dec 25 '22 00:12

RKh


2 Answers

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();
like image 38
Selman Genç Avatar answered Jan 09 '23 15:01

Selman Genç


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();
like image 166
Jon Skeet Avatar answered Jan 09 '23 13:01

Jon Skeet