Cloud Training (Online)

Initializers via Expression Auto Properties in C# 6.0

C# 6.0 Features Series

In one of the previous blog post , i shared an interesting feature in C# 6.0 that demonstrates How to Initialize a Read-Only Auto Properties in C# 6.0 ? .

In this blog post , I will share an extension of the same feature where the Initializers for the auto properties can be any expression including the return value of a method.

Initializers via Expression Auto Properties in C# 6.0

Below is a code snippet demonstrating the usage of the return value of the method to initialize the auto properties in C# 6.0

public class Employee
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime ModifiedDate { get;  } = GetCurrentDateTime();
        public static DateTime GetCurrentDateTime()
            return DateTime.Now;

Note that the Method should be static or else you will receive the below error .

Error    CS0236    A field initializer cannot reference the non-static field, method, or property ‘Employee.GetCurrentDateTime()’


Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.