Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize during declaration and create shorthand getter/setter

Tags:

c#

getter

setter

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;
}
like image 767
roverred Avatar asked Oct 20 '13 22:10

roverred


2 Answers

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

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

Source: MSDN

like image 121
Gobe Avatar answered Oct 07 '22 01:10

Gobe


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;
    }
}
like image 44
Ilya Palkin Avatar answered Oct 07 '22 01:10

Ilya Palkin