C# 6.0 Features Series
- How to try C# 6.0 and Rosyln?
- Getter-only (Read Only) Auto Properties in C# 6.0
- Lambda and Getter Only Auto-Properties in C# 6.0
- Initializers for Read-Only Auto Properties in C# 6.0
- Initializers via Expression Auto Properties in C# 6.0
- C# 6.0 – A field initializer cannot reference the non-static field, method, or property
- Lambda Expression for Function Members in C# 6.0
- Dictionary Initializers (Index Initializers) in C# 6.0
- Expression Bodies on Methods returning void in C# 6.0
- using keyword for static class in C# 6.0
- Unused namespaces in Different Color in Visual Studio 2015
- Null-Conditional Operator in C# 6.0
- Null-Conditional Operator and Delegates
- nameof Operator in C# 6.0
- Contextual Keywords in C#
- String Interpolation in C# 6.0
- Exception Filters in C# 6.0
- Await in Catch and finally block in C# 6.0
Getter-only (Read Only) Auto Properties in C# 6.0
With the earlier versions of C# , you would generally use the the read only backing field for creating a read-only property and initialize the read-only backing field in the constructor of the class. The auto implemented properties required both the getter and the setter.
Below is a code snippet on how this is done in the earlier version of C#
public class Employee { public string Name { get; set; } public string Designation { get; set; } private readonly DateTime _DateOfJoining; public DateTime DateOfJoining { get { return _DateOfJoining; } } public Employee(string name,string designation) { Name = Name; Designation = designation; _DateOfJoining = DateTime.Now; } }
Getter-only (Read Only) Auto Properties in C# 6.0
C# 6.0 has a feature that allows the Getter-only auto-properties and can be assigned in the constructor. This lets the developers use the auto implemented properties to implement the read-only property.
public class Employee { public string Name { get; set; } public string Designation { get; set; } // Auto Implemented Getter Only (readonly) property in C# 6.0 public DateTime DateOfJoining { get; } public Employee(string name,string designation) { Name = Name; Designation = designation; DateOfJoining = DateTime.Now; } }