Saturday, 25 July 2015

Setting a Default Value on a C# Property

Came across this little beauty for setting a default value on a C# 5.0 and below property so you can condense this:

private int myInt = 3;
public int MyInt
{
    get { return this.myInt; }
    set { this.myInt = value; }
}

Into this:

[System.ComponentModel.DefaultValue(3)]
public int MyInt { get; set; }

Obviously there's an array of variable types that can be used.

C# 6.0 is due to have a further tweak to allow us to do this:

public int MyInt { get; set; } = 3;

Sweeet :)

No comments:

Post a Comment