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

}

No Responses

Leave a Reply