In the earlier version of C# , if you want a read-only property , you would end up having a backing field which is initialized in the constructor.

public class Employee
{

        private readonly DateTime _CreatedDate;
        public DateTime CreatedDate
        {
            get
            {
                return _CreatedDate;
            }
        }
        public Employee()
        {
            _CreatedDate = DateTime.Now;
        }
}

In C# 6.0 , the auto-implemented properties can be used to implement read-only property using the auto-property initializer as shown below.

Auto-Property Initializers for Read-Only Properties in C# 6.0

public class Employee
{
    public DateTime CreatedDate { get;  } = DateTime.Now;       
}

Leave a Reply

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

Liked this content?. Please spread the word :)

  • RSS
  • Twitter
    Visit Us
    Follow Me