edit: is it "same as a public readonly field, but it's a property"?
edit: is it "same as a public readonly field, but it's a property"?
Similar to the JVM, the CLR can offer binary compatibility of libraries, which is something Microsoft cares a great deal about. Changing a public readonly field in to a public readonly property is source-compatible, but not binary-compatible. That's why properties are generally preferred, even when you don't strictly need one. The language was actively discouraging either immutability or binary-compatibility by making it more verbose to get a trivial readonly property.
In its simplest form, it means you can do this:
public property Foo { get; } = 5;
Your class now has a Foo property that nobody can set, not even methods in the class itself, but that can be publicly read.These become a lot more useful with primary constructors (also a new C# 6 feature):
public class MyImmutableClass(int usersFoo) {
public property Foo { get; } = usersFoo;
}
This will create a constructor on the class that takes the usersFoo argument, and immediately assign the value of that argument to your read-only automatic property. It makes immutable classes a lot easier to create, and guarantees that they'll stay immutable.edit: Permit made it clear that primary contructors have been dropped from the C# 6 spec. You'll just have to assign your readonly properties from regular constructors then :)
Internally, .Net automatic properties are compiled with a backing field and a getter and setter method. In the case of a read-only auto property, they will omit the setter, so there is no public artifact that could be abused.
A bit messy, but an overview with code samples can be found at http://msdn.microsoft.com/en-us/magazine/dn683793.aspx
Primary constructors have been removed: https://roslyn.codeplex.com/discussions/568820
thanks!
"Automatic" is clear, "getter-only" is clear, but "automatic getter-only" leaves me scratching my head.
public bool IsOpen{get; private set;}
public void Open(){
try{
// do some complex work
this.IsOpen = true;
}
catch{
this.IsOpen = false;
}
}
public void Close(){
// do some other work
this.IsOpen = false;
}It's on the 9th slide: https://view.officeapps.live.com/op/view.aspx?src=http%3a%2f...
I often write stuff like this:
public RxProperty<bool> IsFoo{get;private set;}
I could do without the private set.