Why is it illegal to have a private setter on an explicit getter-only interface implementation?
The only way to invoke an explicit interface member is to cast the object to the correct interface and then invoke the member on that interface. But once you've cast to IConnection
, the IConnection.ConnectionString
has no setter.
So there's no way to invoke this private setter method.
The problem is that when an interface member is declared explicitly, the compiler generates a private
implementation with an "unpronounceable" name, and provides no means by which code--even within the implementing class--to refer to that implementation.
Basically, when one says void IFoo.Moo()
, one is saying that one does not wish to define a name Moo
within the class scope; consequently, the compiler won't. In order for private set
to work, the member would have to be a "pronounceable" name, and the fact that the member was explicitly implemented is taken as an indication that one does not want the name to be Moo
.
In practice, the remedy here is probably the same as for many other cases where it's necessary to have an interface implementation whose name is pronounceable, but which is not exposed publicly under its name: declare an interface implementation which does nothing but chain to other members which have the proper accessibility, e.g. if derived classes should not be able to affect the value the value:
private readonly int _foo = whatever;
public int IFOO.Foo { get {return _foo;}}
or, if derived classes should be able to affect it, either
protected int _foo = whatever;
public int IFOO.Foo { get {return _foo;}}
or
private int _foo = whatever;
protected virtual int setFoo(int value) { _foo = value; }
protected virtual int getFoo() { return _foo; }
public int IFOO.Foo { get {return getFoo();}}
In vb.net, interfaces may be implemented using protected class members, but C# offers no such facility.