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.
Old thread. Looks like Microsoft heard and this feature is available in .Net Framework 4.6+ (C# 6+) You can use it like
public string MyValue { get; set; } = "My Default";
If you are using C#5 and earlier, you have to do it in a constructor.
but since C# 6.0, the ability to have auto property initializers is included, and the syntax is:
public int myage { get; set; } = 33;
Assign the default property value in the class constructor.
class MyClass
{
public MyClass()
{
IsTrue = true;
IsFalse = false;
}
public bool IsTrue { get; set; }
public bool IsFalse { get; set; }
[...]
public void Something()
{
var isTrue = this.IsTrue;
var isFalse = this.IsFalse;
}
}