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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...