initialize during declaration and create shorthand getter/setter

roverred picture roverred · Oct 21, 2013 · Viewed 9.3k times · Source

How do I initialize the member variables during declaration and create the getter/setter shorthand? Is it possible or do I have to use the constructor to assign the value?

For example I want to do something similarl to this

public class Money
{
   public int dollars = 200 {get; set;}
}

or

public int dollars = 200;

dollars 
{
    get;
    set;
}

Answer

Gobe picture Gobe · Jan 22, 2016

In C# 6 and later, you can initialize auto-implemented properties similarly to fields:

public string FirstName { get; set; } = "Jane";

Source: MSDN