constructor - What is the best way to give a C# auto-property an initial value?

ID : 395

viewed : 256

Tags : c#constructorgettersetterautomatic-propertiesc#





Top 5 Answer for constructor - What is the best way to give a C# auto-property an initial value?

vote vote

94

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher 

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

vote vote

83

Edited on 1/2/15

C# 6 :

With C# 6 you can initialize auto-properties directly (finally!), there are now other answers that describe that.

C# 5 and below:

Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway...

public class DefaultValuesTest {         public DefaultValuesTest()     {                        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))         {             DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];              if (myAttribute != null)             {                 property.SetValue(this, myAttribute.Value);             }         }     }      public void DoTest()     {         var db = DefaultValueBool;         var ds = DefaultValueString;         var di = DefaultValueInt;     }       [System.ComponentModel.DefaultValue(true)]     public bool DefaultValueBool { get; set; }      [System.ComponentModel.DefaultValue("Good")]     public string DefaultValueString { get; set; }      [System.ComponentModel.DefaultValue(27)]     public int DefaultValueInt { get; set; } } 
vote vote

70

When you inline an initial value for a variable it will be done implicitly in the constructor anyway.

I would argue that this syntax was best practice in C# up to 5:

class Person  {     public Person()     {         //do anything before variable assignment          //assign initial values         Name = "Default Name";          //do anything after variable assignment     }     public string Name { get; set; } } 

As this gives you clear control of the order values are assigned.

As of C#6 there is a new way:

public string Name { get; set; } = "Default Name"; 
vote vote

65

Sometimes I use this, if I don't want it to be actually set and persisted in my db:

class Person {     private string _name;      public string Name      {          get          {             return string.IsNullOrEmpty(_name) ? "Default Name" : _name;         }           set { _name = value; }      } } 

Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to.

Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving.

Hope that helps!

vote vote

56

In C# 6.0 this is a breeze!

You can do it in the Class declaration itself, in the property declaration statements.

public class Coordinate {      public int X { get; set; } = 34; // get or set auto-property with initializer      public int Y { get; } = 89;      // read-only auto-property with initializer      public int Z { get; }            // read-only auto-property with no initializer                                      // so it has to be initialized from constructor          public Coordinate()              // .ctor()     {         Z = 42;     } } 

Top 3 video Explaining constructor - What is the best way to give a C# auto-property an initial value?







Related QUESTION?