Alan
Alan

Reputation: 2644

C# Automatic Properties -- setting defaults

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.

Upvotes: 6

Views: 600

Answers (6)

Michael
Michael

Reputation: 909

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

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 9

Oded
Oded

Reputation: 499002

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.

Upvotes: 3

Toby
Toby

Reputation: 7544

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

Upvotes: 2

Mike Mooney
Mike Mooney

Reputation: 11989

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

Upvotes: 2

sbenderli
sbenderli

Reputation: 3784

Set the default in your constructor:

this.MyProperty = <DefaultValue>;

Upvotes: 5

Related Questions