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;
    }
}
Youngs
  • 147
  • 1
  • 6

2 Answers2

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

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 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. – Youngs May 18 '12 at 11:13
0

Because private means accessible within the class that owns property.

Johnny_D
  • 4,592
  • 3
  • 33
  • 63
  • `within the class that owns property` and nested classes within that class, so as @Oded describes `private to the enclosing type`.. – Jalal Said May 18 '12 at 11:03