Cloud Training (Online)




C# 6.0 – A field initializer cannot reference the non-static field, method, or property

When using the auto property initializer and trying to initialize the auto property with a value from method , you might end up with the below error

C# 6.0 – A field initializer cannot reference the non-static field, method, or property.

image

For example , the below code snippet will give the error.

public class User
{
        public DateTime CreatedDate { get;  } = GetCurrentDate();

        public DateTime GetCurrentDate()
        {
            return DateTime.Now;
        }
}

The reason for the error is that the method GetCurrentDate is NOT marked as static . Setting the method static as shown below will resolve this error.

public class User
{
        public DateTime CreatedDate { get;  } = GetCurrentDate();

        public static DateTime GetCurrentDate()
        {
            return DateTime.Now;
        }
}

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.