Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value using "short style" properties in VS2008 (Automatic Properties)?

How can I setup a default value to a property defined as follow:

public int MyProperty { get; set; }

That is using "prop" [tab][tab] in VS2008 (code snippet).

Is it possible without falling back in the "old way"?:

private int myProperty = 0; // default value
public int MyProperty
{
    get { return myProperty; }
    set { myProperty = value; }
}

Thanks for your time. Best regards.

like image 222
Tute Avatar asked Oct 15 '08 21:10

Tute


2 Answers

Just set the "default" value within your constructor.

public class Person
{
   public Person()
   {
       this.FirstName = string.Empty;
   }

   public string FirstName { get; set; }
}

Also, they're called Automatic Properties.

like image 114
Chris Pietschmann Avatar answered Sep 20 '22 06:09

Chris Pietschmann


My preference would be to do things "the old way", rather than init in the constructor. If you later add another constructor you'll have to be sure to call the first one from it, or your properties will be uninitialized.

like image 33
Jon B Avatar answered Sep 21 '22 06:09

Jon B