Assign the Default Value to a Property or Auto-implemented property
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.
// 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.
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.
private string _name;
[DefaultValue("unknown")]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}