Configuring a private setter using an object initializer

Why is it possible to use an object initializer to set the private set auto property when the initiator is called from the class to which the auto property belongs? As an example, I have included two classes.

public class MyClass { public string myName { get; private set; } public string myId { get; set; } public static MyClass GetSampleObject() { MyClass mc = new MyClass { myName = "Whatever", // <- works myId = "1234" }; return mc; } } public class MyOtherClass { public static MyClass GetSampleObject() { MyClass mc = new MyClass { myName = "Whatever", // <- fails myId = "1234" }; return mc; } } 
+4
source share
2 answers

The private modifier for setter is private for the closing type.

That is, a property can only be specified by the containing type.

If this is not the case, you can never set the property, and it will be effectively read-only.

From MSDN - private (link to C #) :

Private members are only accessible within the body of the class or structure in which they are declared.

+3
source

Because private funds are available in the class to which the property belongs.

0
source

Source: https://habr.com/ru/post/1413143/


All Articles