Press "Enter" to skip to content

How to set a default value for a property in C#

Here’s how to set default property values for properties in C#

public class Person
{
	public string Name { get; set; } = "Unknown";
	private string _preferredLanguage = "BASIC";
	public string PreferredLanguage
	{
		get { return _preferredLanguage; }
		set { _preferredLanguage = value; }
	}
	public List<string> KnownLanguages { get; } = new List<string>() { "BASIC" };
}
void Main()
{
	Person person = new Person();
	
	Console.WriteLine(person);
	person.Name = "Scott";
	person.KnownLanguages.Clear();
	person.KnownLanguages.Add("C#");
	person.PreferredLanguage = "C#";
	Console.WriteLine(person);
}

On line 3, we have an auto-property “Name”. To set its default value, after the “{ get; set; }” add an equal sign, the value you want for the default, and a semi-colon.

On line 6, we have the “PreferredLanguage” property, which uses a backing variable to hold the property’s value. For properties with backing variables, you generally set the backing variable to the default value, like we do on line 5 here.

On line 12, we have the “KnownLanguages” property, whose datatype is List<string>. Just like with the “Name” property, we set the default value by adding an equal sign, the value we want for the default, and a semi-colon.

Something you may see with List, Collection, and ObservableCollection properties is that they don’t have a “set”, only a “get”, only with the initial default value. This way, other classes cannot set the property to a new List<T> object. Other classes can only Add, AddRange, Remove, and Clear values on the initial List<T> object.

The code on lines 15-27 shows instantiating a Person object and displaying it with the default values, then setting the properties to new values and re-displaying the object with the new property values.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.