Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to set a default value for automatic properties?

I have some interface and class implementing that interface:

public interface IWhatever {
   bool Value { get; set;}
}

public class Whatever : IWhatever {
   public bool Value { get; set; }
}

Now, does C# allow the Value to have some default value without using some backing field?

like image 768
Yippie-Ki-Yay Avatar asked May 04 '11 15:05

Yippie-Ki-Yay


1 Answers

Update

As of C# 6 (VS2015) this syntax is perfectly valid

public bool Value { get; set; } = true;

as is setting a value for a readonly property

public bool Value { get; } = true;

The old, pre C# 6 answer

Spoiler alert for those of an excitable nature: The following code will not work

Are you asking, "Can I do this?"

public bool Value { get; set; } = true;

No, you can't. You need to set the default value in the constructor of the class

like image 69
Binary Worrier Avatar answered Nov 28 '22 06:11

Binary Worrier