Read-only property in C # 6.0

Microsoft will introduce a new syntax in C # 6 that will allow you to set a read-only property, as shown below:

public class Animal { public string MostDangerous { get; } = "Mosquito"; } 

I am wondering what the added value of this approach is.

What is the difference just by writing:

 public class Animal { public const string MostDangerous = "Mosquito"; } 

or even:

 public class Animal { public string MostDangerous { get { return "Mosquito"; } } } 
+5
source share
3 answers

Your example is a bit limited. Take a look at this snippet:

 class Foo { public DateTime Created { get; } = DateTime.Now; // construction timestamp public int X { get; } public Foo(int n) { X = n; } } 

Properties are read-only for each instance and can be set from the constructor. Very different from the const field, the value of which must be determined at compile time. The property initializer is a separate function and follows the rules and restrictions of field initializers.

+10
source

The new syntax is an attempt to reduce C # verbosity. It is just syntactic sugar. The IL created is similar to the auto property with a getter and backup storage.

+2
source

This improvement for C # was taken directly from VB and eliminates the need to implement the support field and constructor initializer:

 Public ReadOnly dateStamp As DateTime = Datetime.Now 
+1
source

Source: https://habr.com/ru/post/1247799/


All Articles