Set Default Value to Property in C#


Here you will learn how to assign the default value to a property or auto-implemented property in a class.

Default Value of Auto-Implemented Property

In C# 6.0 or higher versions, assign the inline default value to the auto-implemented property, as shown below.

Example: Default Value to Auto-implemented Property
// C#6.0 or higher version
public string Name { get; set; } = "unknown"; 

Using Property Setter

The following example sets the default value to a private property field.

Example: Default Value to Property
private string _name = "unknown";
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}

Using DefaultValue Attribute

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

Example: Default Value to Property
private string _name;
[DefaultValue("unknown")]
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}