ChocapicSz ChocapicSz - 11 months ago 82
C# Question

Property with getter only vs. with getter and private setter

Are these the same?

public string MyProp { get; }


public string MyProp { get; private set; }

I mean in both versions the property can be set in its own class but is readonly for other classes?

Answer Source

public string MyProp { get; } - This is introduced in C# 6.0. And such properties are called read-only auto-properties. Assignments to such members can only occur as part of the declaration or in a constructor in the same class. You can read detailed explanation about it in that MSDN article or in Jon Skeet blog. As explained in that article, such property solves four problem automatically:

  • A read-only-defined backing field
  • Initialization of the backing field from within the constructor
  • Explicit implementation of the property (rather than using an auto-property)
  • An explicit getter implementation that returns the backing field

public string MyProp { get; private set; } - This means that the property is read-only in the outside of this class, but you can change it's value inside of this class.

By the way, you can set read-only auto-properties value using new auto-initialize syntax which is again introduced in C# 6.0:

public string MyProp { get; } = "You can not change me";

It is equal to this code for the previous versions of C#:

private readonly string myProp = "You can not change me"
public string MyProp { get { return myProp ; } }

Or, this in C# 6.0:

public string MyProp { get; }
protected MyClass(string myProp, ...)
    this.MyProp = myProp;

is equal to this in the previous versions:

private readonly string myProp;
public string MyProp { get { return myProp; } }
protected MyClass(string myProp, ...)
    this.myProp = myProp;