Question

What's the easiest/straight-forward way of setting a default value for a C# public property?

// how do I set a default for this?

public string MyProperty { get; set; }

Please don't suggest that I use a private property & implement the get/set public properties. Trying to keep this concise, and don't want to get into an argument about why that's so much better. Thanks.

Was it helpful?

Solution

Set the default in your constructor:

this.MyProperty = <DefaultValue>;

OTHER TIPS

Just initialize it in the constructor:

public class MyClass
{
    public string MyProperty { get; set; }

    public MyClass()
    {
        MyProperty = "default value";
    }
}

Note that if you have multiple constructors, you'll need to make sure that each of them either sets the property or delegates to another constructor which does.

Please don't suggest that I use a private property

That's the standard way to set such defaults. You might not like it, but that what even the automatic properties syntax does after compilation - it generates a private field and uses that in the getter and setter.

You can set the property in a constructor, which will be as close to a default as you can get.

No, it would be nice if you could just mark up the property to indicate the default value, but you can't. If you really want to use automatic properties, you can't set a default in property declaration.

The cleanest workaround I've come up with is to set the defaults in the constructor. It's still a little ugly. Defaults are not colocated with the property declaraion, and it can be a pain if you have multiple constructors, but that's still the best I've found

if you're going to use auto-implementation of properties, the only real option is to initialize the property values in the constructor(s).

As of C# 6.0 you can assign a default value to an auto-property.

public string MyProperty {get; set; } = "Default Value";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top