Is there any way to enforce the rest of my class to access the property setter rather than the backing field? Consider the following clumsy code:
public class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
public void OhDearWhatWasIThinking()
{
_somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
}
}
As far as I know, C# does not provide any mechanism to prevent the class developer from making this mistake. (Auto-properties are clearly not an option in this situation.) Is there a design pattern or practice that can help safeguard against such inadvertant end-arounds?
you can move that logic to an abstract base class:
public abstract class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
//.....
}
then you can be sure no one will instantiate this class, and derived classes will not be able to access the private field.
public class BrittleDerived : Brittle
{
public void DoSomething()
{
// cannot access _somethingWorthProtecting;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With