Setting a private setter using an object initializer
Asked Answered
C

2

7

Why is it possible to use an object initializer to set a private set auto property, when the initializer is called from within the class which owns the auto property? I have included two class as an example.

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;
    }
}
Coley answered 18/5, 2012 at 10:51 Comment(4)
because its in same class scopeShanell
Why wouldn't it be possible?Vanzant
@JonSkeet - OP might think private means within the property scope?Holdfast
@Oded: Possibly - but it would be good for the OP to elaborate.Vanzant
H
5

The private modifier on a setter means - private to the enclosing type.

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

If this was not the case, you would never be able to set the property and it would effectively be read-only.

From MSDN - private (C# Reference):

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

Holdfast answered 18/5, 2012 at 10:52 Comment(1)
I have misunderstood how private setter works. I thought the initializer would not have been in the same scope as the class owning the auto private property and would therefore be accessing the property as if it was an external class. Thank you, all.Coley
K
0

Because private means accessible within the class that owns property.

Kestrel answered 18/5, 2012 at 10:53 Comment(1)
within the class that owns property and nested classes within that class, so as @Holdfast describes private to the enclosing type..Blackfish

© 2022 - 2024 — McMap. All rights reserved.