6 ms·
A getter-only property can only be set on initialization of the class, so either with a fixed value or one from a constructor. That does make it the equivalent
by chton 12y ago
A getter-only property can only be set on initialization of the class, so either with a fixed value or one from a constructor. That does make it the equivalent of a read-only field, but it's a lot easier to keep byte-level parity with future versions.
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 http://msdn.microsoft.com/en-us/magazine/dn683793.aspx
- Permit 12y ago>These become a lot more useful with primary constructors (also a new C# 6 feature): Primary constructors have been removed: https://roslyn.codeplex.com/discussions/568820 https://roslyn.codeplex.com/discussions/568820
- chton 12y agoAha I must have missed that news. I'll update my comment. Can't say I'm sad to see them go, they were useful but turn a complicated class into a clusterfuck. thanks!