How do you give a C# Auto-Property a default value?


Question

How do you give a C# Auto-Property a default value? I either use the constructor, or revert to the old syntax.

Using the Constructor:

class Person 
{
    public Person()
    {
        Name = "Default Name";
    }
    public string Name { get; set; }
}

Using normal property syntax (with a default value)

private string name = "Default Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}

Is there a better way?

1
1712
10/18/2010 7:30:53 AM

Accepted Answer

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

The ability to have auto property initializers is included since C# 6.0. The syntax is:

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

DefaultValueAttribute ONLY work in the vs designer. It will not initialize the property to that value.

See DefaultValue attribute is not working with my Auto Property

2048
7/17/2019 12:38:59 AM

Edited on 1/2/15

C# 6 :

With C# 6 you can initialize auto-properties directly (finally!), there are now other answers in the thread 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; }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon