Search code examples
c#.netpropertiesprivate-members

Why private setter?


What I'm wondering is that why do we need a private setter when we could simply assign the value to the private object directly? Consider the following code:

private int counter = 0;
public int Counter {
    get {
        return counter;
    }
}

I don't see any difference between having a private setter (Counter = 1) vs assigning the value directly to the private object (counter = 1) in the context above.

The only reason I could think about having a private setter is when there is a need to trigger change notifications / events. Other than that do we even need a private setter at all?


Solution

  • If you use an auto property, you don't see the background field:

    public int Counter { get; private set; }
    

    This allows you to have it private for set and public for get, without having to write the backing field yourself.

    Even if you're using a backing field, there are times when you want to still use the property, and not the field. A property setter can actually include other logic (validation/change notification/etc) which may be appropriate to call, but you may want to restrict the access to this to your class.