Getter-only (Read Only) Auto Properties in C# 6.0

C# 6.0 Features Series

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;
      }

}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...