bentford bentford - 1 month ago 10
C# Question

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

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?

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