Understanding Private Developers

I don't understand the need to have private setters that started with C # 2.

Having the setter method for me allows the user to set some variables in this class. However, we will not expose variables directly to users. Instead, we allow them to do this using this public setter method.

This is used for me "encapsulation". There are some arguments that argue that private setters allow you to use encapsulation.

I do not use encapsulation using public configuration methods? Why do we need private setters?

What is the difference between an immutable class and a private setter class?

+45
c #
02 Oct '10 at
source share
11 answers

Logically.

Having a private setter is due to the fact that you can use the auto property:

public int MyProperty { get; set; } 

What would you do if you want to do this read-only?

 public int MyProperty { get; } 

Oh shit !! I cannot access it from my class; I have to create it as a regular property:

 private int myProperty; public int MyProperty { get { return myProperty; } } 

Hmm ... but I lost the "Auto property" function ...

 public int MyProperty { get; private set; } 

AHHH .. it's better !!

+152
Oct 02 '10 at 23:55
source share

A private setter is useful if you have a read-only property and do not want to explicitly declare a reference variable.

So:

 public int MyProperty { get; private set; } 

matches with:

 private int myProperty; public int MyProperty { get { return myProperty; } } 

For non-automatically implemented properties, it gives you a consistent way to set properties from your class, so that if you need validation, etc., you only have one place.

To answer your last question, MSDN has this to say in private setters:

However, for small classes or structures that simply encapsulate a set of values ​​(data) and have little or no behavior, it is recommended that the objects be immutable, while declaring the set accessory as closed.

From the MSDN page in Auto Implemented Properties

+30
Oct 02 '10 at 23:01
source share

It is pretty simple. Private setters allow you to create read-only public or protected properties.

What is it. This is the only reason.

Yes, you can create a read-only property by specifying only a getter, but with automatic injection properties you need to specify both get and set, so if you want the automatically implemented property to be read-only, you should use private setters. There is no other way to do this.

It is true that private setters were not designed specifically for automatically implemented read-only properties, but their use is slightly more esoteric for other reasons, mainly focusing on read-only properties and using reflection and serialization.

+14
Oct 03 2018-10-10T00:
source share

With the introduction of C # 6.0 and the syntax of AutoSource Initializers , private settings are no longer needed for properties that are set only during initialization, both inside and inside the constructor.

These new syntaxes now compile:

Inline Initialized Property

 public class MyClass1 { public string MyProperty { get; } = "Aloha!" } 

Initialized constructor

 public class MyClass2 { public string MyProperty { get; } public MyClass2(string myProperty) { MyProperty = myProperty; } } 
+6
Dec 11 '15 at 12:35
source share

I don't understand the need to have private setters that started with C # 2.

For example, the account class allows the user to add or remove items from the Items property, but it does not allow the user to change the link to Items (that is, the user cannot assign the Items property to an instance of an item list object).

 public class Item { public string item_code; public int qty; public Item(string i, int q) { this.item_code = i; this.qty = q; } } public class Invoice { public List Items { get; private set; } public Invoice() { this.Items = new List(); } } public class TestInvoice { public void Test() { Invoice inv = new Invoice(); inv.Items.Add(new Item("apple", 10)); List my_items = new List(); my_items.Add(new Item("apple", 10)); inv.Items = my_items; // compilation error here. } } 
+4
Oct 03 '10 at 14:21
source share

Say, for example, you are not storing the actual variable through a property, or you are not using a value to calculate something.

In this case, you can either create a method for calculating

 private void Calculate(int value) { //... } 

Or you can do it using

 public int MyProperty {get; private set;} 

In those cases, I would recommend using it later, since the properties refactor each element of the element without changes.

Other than that, even if you say that you map a property to a variable. In this case, inside your code you want to write like this:

 public int myprop; public int MyProperty {get { return myprop;}} ... ... this.myprop = 30; ... ... if(this.MyProperty > 5) this.myprop = 40; 

The above code looks awful since the programmer always needs to carefully use MyProperty for Get and myprop for Set.

Try again for consistency, you can use a private setter that forces Propoerty to read only from the outside, while you can use its setter inside your code.

+3
Oct 02 '10 at 23:19
source share

Encapsulation means that the state of the object occurs only through a certain interface, and because of this, the class can make sure that this state is always correct and corresponds to the purpose of the class.

Thus, in some cases, it is fully consistent with the principle of encapsulation in order to publicly publish the field - all possible values ​​for the field are valid with all other possible values ​​of all other fields, and therefore the programmer can actively decide to freely manipulate the field with external code.

These cases, although mostly limited to classes, which are mostly “plain old data”. They are also not very interesting in this regard, so much about them.

In other cases in other languages, you have the getter and setter method, something like int getId() to get the value and void setId(int val) to update it.

Properties allow you to use the same syntax for reading and writing using methods that we will use to read and write fields. It is a good syntactic sugar, although not vital.

(Actually, because of how reflection works, and in cases like DataBinder.Eval , it may be convenient to have a property, even if the field works fine, but that's another matter).

Until private setters are introduced (in fact, what has changed from C # 2 is the syntax for having a private setter and a public or protected getter in the same block), we could have a private method for working a private setter therefore private setters are really not needed. They are convenient though, although while just syntactic sugar, they are very useful.

Encapsulation is not a question of whether your setters (or getters) are public, private, protected, or internal, but the question of whether they are suitable. Start with the default for each field that is private (and for that matter, readonly ), and then add members (properties or methods) that change these fields if necessary, and make sure that the object remains valid when changed . This ensures that the invariant of the class is preserved, which means that the rules that describe the valid set of states in which it may be are never interrupted (constructors also help by making sure that it starts in this correct state).

As for your last question, to be immutable, it means that the class does not have public, protected or internal setters and there are no public, protected or internal methods that change any fields. There are degrees, in C # three degrees are possible:

  • The entire field of the readonly class instance, so even private code cannot change it. It is guaranteed to be unchanged (everything that tries to change it will not compile), and, possibly, optimization can be performed on the reverse side.

  • The class is immutable from the outside, because none of the public members changes anything, but does not guarantee the use of readonly , so as not to change from the inside.

  • The class is immutable, as can be seen from the outside, although some state changes as part of the implementation. For example. the field can be seen, and therefore, from outside the attempt to get it just gets the same value, the first such attempt actually calculates it, and then saves it for retrieval in subsequent attempts.

+2
Oct 02 '10 at 23:41
source share

I think some people have danced around this, but for me the value of private setters is that you can encapsulate the behavior of a property even inside a class. As Abhishek noted, if you want the property event to change every time the property changes, but you do not want the property to be read / written to the public, you either have to use a private setter, or you should raise the event anywhere you change support field. The latter is error prone because you can forget. In addition, if updating the property value leads to some kind of calculation being performed, or to changing another field or lazily initializing something, then you will also want to wrap this in a private setter, instead of forgetting to do it everywhere, using the support field.

+2
Oct 03 2018-10-03
source share

Yes, you use encapsulation with properties, but there are more nuances to encapsulation than just controlling how properties are read and written. Rejecting a property that needs to be set outside the class can be useful for both reliability and performance.

An immutable class is a class that does not change after it is created, so private setters (or not configured at all) are required to protect properties.

Private setters have become more commonly used with property shorthand, which was introduced in C # 3. In C # 2, the installer was often simply omitted, and personal data was available directly during installation.

This property:

 public int Size { get; private set; } 

matches with:

 private int _size; public int Size { get { return _size; } private set { _size = value; } } 

except that the name of the supporting variable is internally generated by the compiler, so you cannot access it directly.

With a shortened property, a private setter is needed to create a read-only property, since you cannot directly access the backup variable.

+1
Oct 02 '10 at 23:29
source share

I don't understand the need to have private setters that started with C # 2.

Example usage example:

I have an instance of the 'UserInfo' application object that contains the SessionTokenIDV1 property that I do not want to show to users of my class.

I also need the ability to set this value from my class.

My solution was to encapsulate the property as shown in the picture and make setter private so that I can set the value of the session token without letting the code instance also set it (or even see it in my case)

 public class UserInfo { public String SessionTokenIDV1 { get; set; } } public class Example { // Private vars private UserInfo _userInfo = new UserInfo(); public string SessionValidV1 { get { return ((_userInfo.SessionTokenIDV1 != null) && (_userInfo.SessionTokenIDV1.Length > 0)) ? "set" : "unset"; } private set { _userInfo.SessionTokenIDV1 = value; } } } 

Edit: Fixed code tag. Change: Errors were fixed in the example.

+1
Dec 10 '14 at 16:30
source share

You need a private setter if you want to support the following scenario (not only for this, but this should point to one good reason): You have a property that is read-only in your class, that is, only the class itself can change it, but he can change it after creating the instance. For bindings, you will need to fire the PropertyChanged event, preferably it should be done in a (private) property setting device. In fact, you can just fire the PropertyChanged event from another place in the class, but using a private setter for this is “good citizenship”, because you do not distribute property change triggers throughout the class, but save it on where it belongs.

0
Oct. 02 '10 at 23:43
source share



All Articles