1

I was expecting the assignment to this.GetProp to fail at compile time due to no set supported for the property. This code compiled just fine with VS2015 & NET461.

public class Example
{
    public Example(string val)
    {
        this.GetProp = val;
        this.GetSetProp = val;
    }

    public string GetProp { get; }
    public string GetSetProp { get; set; }
}

Is there are implied private access to the backing field in auto properties?

Ken Brittain
  • 2,255
  • 17
  • 21
  • 12
    You can set a property's value in the constructor, even when it's getter-only, just like you can assign to `readonly` variables – Jakub Dąbek Aug 09 '17 at 12:09

2 Answers2

3

This is a newly introduced feature in C# 6.0. See the C# 6.0 Language specification, section 10.7.3 Automatically implemented properties:

If the auto-property has no set accessor, the backing field is considered readonly (§10.5.2). Just like a readonly field, a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.

(Emphasis mine)

adjan
  • 13,371
  • 2
  • 31
  • 48
2

This is a getter-only auto-property introduced in C# 6. The backing field is implicitly declared as readonly, hence you can set it from the constructor.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64