John Gathogo
John Gathogo

Reputation: 4655

Method invocation in "Implement Interface Explicitly" classes

I would like to understand what Implement Interface Explicitly entails in C# based on the contexts/scenarios described below. Lets say I have the following interface:

public interface ITestService
{
    void Operation1();
    void Operation2();
}

Lets say I implement the interface explicitly as shown below, is it possible, using whatever means to call Operation2() from Operation1()?

public sealed class TestService : ITestService
{
    public TestService(){}

    void ITestService.Operation1()
    {
        // HOW WOULD ONE SUCCESSFULLY INVOKE Operation2() FROM HERE. Like:
        Operation2();
    }

    void ITestService.Operation2()
    {

    }
}

What happens differently (under the wraps) to allow testService1 and testService2 declared differently below behave differently?

static class Program
{
    static void Main(string[] args)
    {
        ITestService testService1 = new TestService();      
        testService1.Operation1(); // => Works: WHY IS THIS POSSIBLE, ESPECIALLY SINCE Operation1() AND Operation2() WOULD BE *DEEMED* private?
        // *DEEMED* since access modifiers on functions are not permitted in an interface

        // while ...
        TestService testService2 = new TestService();
        testService2.Operation1(); //! Fails: As expected
    }
}

Upvotes: 1

Views: 75

Answers (2)

Habib
Habib

Reputation: 223207

for your 2nd question

testService1.Operation1(); // => Works: WHY IS THIS POSSIBLE, ESPECIALLY SINCE Operation1() AND Operation2() WOULD BE DEEMED private?

Because the functions in interface are public you can call them. Also, you have explicitly implemented the interface methods, you can't call it against the class object. e.g.

TestService ts = new TestService();
ts.Operation1();// this would cause an error

You may see: Explicit Interface Implementation (C# Programming Guide)

Upvotes: 1

leppie
leppie

Reputation: 117220

void ITestService.Operation1()
{
    ((ITestService)this).Operation2();
}

As for your second question:

All members of interfaces are public. Hence the implementation will be public too.

Upvotes: 1

Related Questions