user76071
user76071

Reputation:

What purpose do publicly exposed explicit interfaces serve?

What's the point of a public explicit interface and how does this differ from private?

interface IYer
{
    void Hello();
}

interface INer
{
    void Hello();
}

class MyClass : IYer, INer
{
    public void IYer.Hello()
    {
        throw new NotImplementedException();
    }

    public void INer.Hello()
    {
        throw new NotImplementedException();
    }
}

Upvotes: 0

Views: 239

Answers (3)

JasonTrue
JasonTrue

Reputation: 19644

I'm not going to address the code above, which I believe has errors pointed out by others, but I'll answer the question itself.

  1. With explicit interface implementation, you can support multiple interfaces that have conflicting names.
  2. You avoid emphasizing the availability of an interface to clients, when the interface isn't important to most consumers of that class. This is because most languages in the Dotnet framework will require an explicit cast to the interface before you can use methods from explicitly implemented interfaces.
  3. Less important, but I've used them to prevent accidental use of a method or property accessor: Using Explicit Interfaces to prevent accidental modification of properties in C#

Upvotes: 1

Igor Zevaka
Igor Zevaka

Reputation: 76610

There is no public explicit interface implementation. The only way to implement an interface explicitly is to have the method have default accessibility with the interface name prepended to the method name:

class MyClass : IYer, INer
{
    //compiles OK
    void IYer.Hello()
    {
        throw new NotImplementedException();
    }

    //error CS0106: The modifier 'public' is not valid for this item
    public void INer.Hello()
    {
        throw new NotImplementedException();
    }
}

This is what MSDN has to say about this:

The public keyword is not allowed on an explicit interface declaration. In this case, remove the public keyword from the explicit interface declaration.

Upvotes: 1

Kirk Woll
Kirk Woll

Reputation: 77616

The biggest difference is that your public explicit interfaces are not legal and will not compile. In fact, you should be getting the error, "The modifier 'public' is not valid for explicit interface implementations."

Upvotes: 0

Related Questions