Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding private setters

Tags:

c#

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?

like image 485
Dene Avatar asked Oct 02 '10 22:10

Dene


People also ask

What is a private setter?

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.

What is the difference between set and private set?

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.

Can getters and setters be private?

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.

Should Java setters be private?

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.


1 Answers

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!!

like image 132
ktutnik Avatar answered Nov 10 '22 01:11

ktutnik