6
votes

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.

6
OT: I think you mean a private field - Douglas
I think you are confusing the concepts of public/private and automatic properties vs. manually-implemented properties with backing fields. These concepts are independent. - John Saunders

6 Answers

9
votes

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.

5
votes

Set the default in your constructor:

this.MyProperty = <DefaultValue>;
3
votes

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.

2
votes

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

2
votes

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

1
votes

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

public string MyProperty {get; set; } = "Default Value";