How to hide the backing field from the rest of the class

1.5k Views Asked by At

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?

1

There are 1 best solutions below

3
Jonesopolis On BEST ANSWER

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;
     }
}