Access modifiers on interface members in C#

access-modifiers, c#, explicit-interface, interface

Solution

Explicit interface implementation does not let you specify any access modifiers. When you implement an interface member explicitly (by specifying the interface name before the member name), you can access that member only using that interface. Basically, if you do:

System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
    get { return properties; }
    set { properties = value; }
}

You can't do:

MyClass x = new MyClass();
var test = x.Properties; // fails to compile
// You should do:
var test = ((IWorkItemControl)x).Properties; // accessible through the interface

There are several use cases for EII. For example, you want to provide a `Close` method for your class to free up acquired resources but you still want to implement `IDisposable`. You could do:

class Test : IDisposable {
    public void Close() {
        // Frees up resources
    }
    void IDisposable.Dispose() {
        Close();
    }
}

This way, the consumers of class can only call `Close` directly (and they won't even see `Dispose` in Intellisense list) but you can still use the `Test` class wherever an `IDisposable` is expected (e.g. in a `using` statement).

Another use case for EII is providing different implementations of an identically named interface member for two interfaces:

interface IOne {
   bool Property { get; }
}

interface ITwo {
   string Property { get; }
}

class Test : IOne, ITwo {
   bool IOne.Property { ... }
   string ITwo.Property { ... }
}

As you see, without EII it's not even possible to implement both interfaces of this example in a single class (as the properties differ just in return type). In other cases, you might want to intentionally provide different behavior for individual views of a class through different interfaces.

Problem

I am getting a compile error from the following property. The error is: "The modifier 'public' is not valid for this item" ``` public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties { get { return properties; } set { properties = value; } } ``` but if I remove the `IWorkItemControl` it compiles fine. Why am I getting this error and what is the difference of having / not having the interface name in the signature?

Original source