12

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;
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
roverred
  • 1,841
  • 5
  • 29
  • 46

4 Answers4

36

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

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

Source: MSDN

Gobe
  • 2,559
  • 1
  • 25
  • 24
6

Either

public class Money
{
    private int dollars = 200;
    public int Dollars
    {
        get { return dollars; }
        set { dollars = value; }
    }
}

or

public class Money
{
    public int Dollars { get; set; }

    public Money() 
    {
        Dollars = 200;
    }
}
Ilya Palkin
  • 14,687
  • 2
  • 23
  • 36
5

Unfortunately there is currently no way to achieve this.

You must either assign the default value when you declare the properties backing field or assign the default value from the constructor if you are using an automatic property.

User 12345678
  • 7,714
  • 2
  • 28
  • 46
3
public class Money
{
  public int Dollars {get;set;}

  public Money()
  {
    Dollars = 200;
  }
}
Holystream
  • 962
  • 6
  • 12