Question

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?

Was it helpful?

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.

OTHER TIPS

Using property instead of private variable is a better way of accessing it even if its from within the same class so that if you have some logic in the setter you don't have to repeat it each time you set the value. Even if you don't have logic its better to use property as you might need to add some logic in future. It will be a single point of entry for setting the value.

Also with auto implemented properties you don't need to define a private variable so its use for that situation as well.

private int counter = 0;
public int Counter {
    get {
        return counter;
    }
    private set {
        if(value > 0)
        {
            counter = value;
        }
    } 
}

Getters and setters are usually public, and restrict how the variable can be used by other classes.

Getters and setters often contain logic that applies when changing their values. Preventing invalid assignments, triggering events, that sort of thing. So it could certainly be usefull to write a private setter if a variable is only to be changed within the same class. If you only want to make simple changes, like X++ or x = whatever, then there probably isn't any point in a private setter method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top