views:

641

answers:

3

Hi,

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.

+7  A: 

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.

Chris Pietschmann
FWIW, setting a default value is inefficient if you happen to change the value in any of your constructors.At the company I work for, we actually consider it to be a "code smell" to have a default value because then we have to go and see if it's overwritten in any of the constructors.
David Mitchell
thanks david, will keep that in mind
Matías
+2  A: 

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.

Jon B
Sure, but calling one of the constructors from all the others is usually what you should be doing anyway. It's a pretty standard pattern: The constructors with fewer parameters pass the default values to the constructor with the most parameters.
Kyralessa
A: 

[DefaultValue("MyFirstName")] public string FirstName { get; set; }

Doesn't work, but it really ought to be made to.
Simon