C # How to set default value for auto properties?

I have an interface and a class implementing this interface:

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

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

Now, C#allows you to Valuehave some default value without using some support field?

+5
source share
6 answers

Update

As in C # 6 (VS2015), this syntax is perfectly correct

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

as sets the readonly property

public bool Value { get; } = true;

Old pre C # 6 answer

Exciting spoiler warning: The following code will not work

You ask: "Can I do this?"

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

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

+13

, false, .

, , , false, :

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

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

    public Whatever()
    { 
        Value = true;
    }
}
+2

false. true, .

public class Whatever : IWhatever 
{
   public bool Value { get; set; }
   public Whatever()
   {
       this.Value = true;
   }
}
+1

Value false, .

0

Value , . Whatever.

0

.

//constructor
public Whatever()
{
   Value = true;
}

public bool Value { get; set; }

, , ( ).

0

All Articles