0

Why an explicit interface member implementation, don't have modifier

public interface ITest
{
    string Id { get; }
}

public class TestSeparately : ITest
{
    //Why an explicit interface member implementation, don't have modifier
    string ITest.Id
    {
        get { return "ITest"; }
    }
}
Babu Kumarasamy
  • 329
  • 2
  • 6
  • 15

2 Answers2

0

From MSDN

It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.

Because of this, none of the access modifiers like public, protected or private would make any sense.

Note that this won't work:

TestSeparately ts = new TestSeparately();
string id = ts.Id; // compiler error, because Id is not a public property of TestSeparately

You'd need to case it to ITest:

string id = ((ITest)ts).Id; 

So access modifiers are of no use for explicit interface implementations.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

By default every member in an interface is public and it has to be that way because interface defines a certain prototype. However a class or structure can inherit from multiple interfaces and it may well be the case that those interfaces have same methods or properties. Consider the following:

public interface ITest
{
    string Id { get; }
}

public interface ITest1
{
    string Id { get; }
}

public class TestSeparately : ITest, ITest1
{
//Why an explicit interface member implementation, don't have modifier
    string ITest.Id
    {
        get { return "ITest"; }
    }
    string ITest1.Id
    {
        get { return "ITest1"; }
    }
}

Now if there is a way to cast class to interface implicitly and access members that way, asking property value Id from TestSeparately, I.e return value of TestSeparately.Id is what? Which interface compiler should implicitly cast to and return ID? Is it ITest.Id or ITest1.I'd? See the problem so yes there no modifier in explicit implementation and explicit casting is always required to determine which interface should be targeted and as I said, public is the only access modifier by force and not changeable.

Mukesh Adhvaryu
  • 642
  • 5
  • 16