The next new feature of the C# 6.0 is auto-property initializers and get-only auto property. The main problem that they suppose to solve is immutable type declaration. Before C# 6.0, if you want to create immutable type with properties, you have no possibility to use auto property:
1
| public string Property { get ; set ; } |
So, you were forced to use regular get-only (read-only) property with read-only backing field:
1
2
3
4
5
6
7
| private readonly string prop; public string Prop { get { return prop; } } public Ctor() { prop = "value" ; } |
Now, with C# 6.0, you can write:
1
| public string Prop { get ; } = "value" ; |
Of course, you can use property initialization not only with read-only auto property. Regular one is also working well:
1
| public string Prop { get ; set ; } = "value" ; |
The same as static one:
1
| public static string Prop { get ; set ; } = "value" ; |
You can even use expressions to initialize property:
1
2
3
4
5
| public string Prop { get ; set ; } = InitializeProperty(); public static string InitializeProperty() { return "value" ; } |
No comments:
Post a Comment