tags:

views:

188

answers:

5

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.

+5  A: 

Set the default in your constructor:

this.MyProperty = <DefaultValue>;
sbenderli
isn't the `this` statement redundant?
Jimmy
yes, but some consider it to be good coding practice.
sbenderli
+2  A: 

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.

Oded
No argument there -- I'm just trying to keep non-critical code concise.
Alan
@Alan If you have more than one constructor then it will no longer be concise because you will have to start making sure that initialization occurs in all code paths. Using a private backing field you can have a single **concise** place to initialize that property.
AaronLS
@AaronLS you could probably be alright if you just chain your constructors.
Alan
+8  A: 

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.

Jon Skeet
another property or another ctor?
jk
Thanks Jon, but sbenderli got to it first :). For some reason I incorrectly assumed the "default value" would overwrite what's sent in the inialization.
Alan
@jk: Another constructor. Doh. Editing.
Jon Skeet
+2  A: 

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

Mike Mooney
+1  A: 

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

Toby