Set a default value to a property

No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted to the constructor) to set the default values.

If you have several overloads for your constructor, you may want to look at constructor chaining.

Using C# 6+, you are able to do something like this…

public string MyValue { get; set; } = "My Default";

Oh, it gets more fun because people have even requested something like this…

// this code won't compile!
public string MyValue {
    private string _myValue;
    get { return _myValue ?? "My Default"; }
    set { _myValue = value; }

… the advantage being that you could control the scope of the field to only be accesible in the property code so you don’t have to worry about anything else in your class playing with the state without using the getter/setter.

Leave a Comment