I thought the @adrianbanks answer could be improved on mine, but I donโt think it really (despite being excellent) - because you have no guarantee that the public interface instance passed to you also implements the internal one - This also applies to this decision. It also exists that it only works if the type of implementation is internal - this is not good if you want to provide public types as standard implementations of an interface or as the basis for a hierarchy.
This is what I use. Given:
interface myInterface { string myProperty { get; set; } } public interface myPublicInterface { string myProperty { get; } }
At first you cannot make myPublicInterface inherit myInterface , because the compiler will moan about inconsistent availability. That way, you can explicitly implement the internal using the property support tool, and then implement the public one implicitly:
public class MyClass : myInterface, myPublicInterface { private string _myProperty; string myInterface.myProperty { get { return _myProperty; } set { _myProperty = value; } } public string myProperty { get { return _myProperty; } } }
Note. In some cases, the getter may not be suitable for a private third-party user, but it may be some kind of logic that calculates values โโfrom other properties. In this case - to keep it DRY - you can put the logic in a public getter and leech, which for an explicit getter:
string myInterface.myProperty { get { return MyProperty; } set { } } public string myProperty { get { } }
You can do it differently, but you have to make the terrible look of the built-in interface:
string myInterface.myProperty { get { } set { } } public string myProperty { get { return ((myInterface)this).myProperty; } }
What you should try to avoid when possible.
source share