Getter only auto-properties - C# 6 Language New features

In previous article we discussed simple yet very useful C#6 new feature "Auto Property Initializers". 
In this article I am going to share another feature -"Getter only auto properties". No need to make your property set accessor private, Just remove it from the property Initialization.

List of all C# 6 New features

In Previous version of C# we need to declare set accessor as private to make set accessor inaccessible. In our example we declare Email set accessor as private. We only assign value through constructor. When we will use Student class in other class and try to set Email value, it will throw error "The property or indexer '' cannot be used in this context because the set accessor is inaccessible"
 public class Student
   public string Name { get; set; }
   public string Email { get; private set; }
   public Student()
     Name = "Bhavik Patel";
     Email = "";
This is C# 6.0 example
public class Student
  public string Name { get;} = "Bhavik Patel";
In C# 6.0 Microsoft introduce new feature. In Getter only auto property feature Getter and Setter both are not compulsory required. In our example we don't have to declare setter explicitly. 
If we initialize Student class in other class and try to set Name property value then it will through error "Property or indexer 'Student.Email' cannot be assigned to -- it is read only"

Summary: using Getter only auto properties feature you can make your entity read-only directly, with out declaring set accessor private.


Popular posts from this blog

12 opensource and free MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in