I don't understand the need of having private setters which started with C# 2.
Having a setter method for me is letting the user to set some variables in that class. In doing so, we will not expose the variables directly to the users. Instead we let them do it through this public setter method.
This for me is using "encapsulation". There are some arguments out there which claim that private setters will let you apply encapsulation.
Am I not using encapsulation by using public setter methods? Why do we need private setters?
What is the difference between immutable class and a class with private setters?
private setters are same as read-only fields. They can only be set in constructor. If you try to set from outside you get compile time error. public class MyClass { public MyClass() { // Set the private property.
Setter pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed before any action methods. Private setter means the variable can be set inside the class in which it is declared in. It will behave like readonly property outside that class's scope.
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
Have you ever heard about a property? A property is a field that has "built-in" accessors (getters and setters). Java, for instance, doesn't have properties, but it's recommended to write the getters and setters to a private field.
Logically.
The presence of a private setter is because you can use auto property:
public int MyProperty { get; set; }
What would you do if you want to make it readonly?
public int MyProperty { get; }
Oh crap!! I can't access it from my own class; I should create it like a normal property:
private int myProperty; public int MyProperty { get { return myProperty; } }
Hmm... but I lost the "Auto Property" feature...
public int MyProperty { get; private set; }
AHHH.. that is better!!
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