Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Even though this is an older Thread i'd like to add some new way implemented in C# > Vers. 6:

https://msdn.microsoft.com/de-de/library/bb384054.aspx

public int MyInt { get; set; } = 0;
public string MyString { get; set; } = "Lorem Ipsum";

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top