This article is about looking at a specific C# feature and see how the functionality has been changed as each new C# version is released.
It’s nice to look at “What’s New” articles but sometimes I find myself unable to remember at which version a specific feature can be used.
CS1
Starting from the first release of C# we had properties defined as follows.
class CS1 { private string _data; public string Data { get { return _data; } set { _data = value; } } }
CS2
CS2 allowed us to declare our getter or setter as private which made it only accessible to the class that created it. You cannot set both to private, which would not make sense.
class CS2 { private string _data1; private string _data2; public string Data1 { private get { return _data1; } set { _data1 = value; } } public string Data2 { get { return _data2; } private set { _data2 = value; } } }
CS3
This is when Automatic Properties first appeared. It took away the need to write boilerplate code when we were just setting and getting.
class CS3 { public string Data1 { get; set; } public string Data2 { private get; set; } public string Data3 { get; private set; } }
CS4
Nothing changed.
CS5
Nothing changed.
CS6
This saw three new features added. We can created a read-only auto property. The field is updated in the class that created it. Auto property initialisers enables us to give an initial value. Prior to CS6 we would have done this in the constructor. Expression-bodied Function Members for Read-only Properties allows us to add expression bodies with a lambda expression. It makes the code more succinct.
class CS6 { // Read-only auto properties. No setter. public string Data1 { get; } // Auto Property Initializers public string Data2 { private get; set; } = "data2"; public string Data3 { get; private set; } = "data3"; public string Data4 { get; } = "data4"; // Expression-bodied Function Members for Read-only Properties public string Data5 => $"{Data2} {Data3}"; }
CS7
Expression-bodied Function Members has been extended to setters now. You would not use it for the example below because we are adding boilerplate code back in. If you had a property with some logic, it can make the code more succinct.
class CS7
{
private string _data1;
public string Data1
{
get => _data1;
set => this._data1 = value;
}
}
CS7.1
Nothing changed.
CS7.2
Nothing changed.