开发者

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 Va开发者_StackOverflow社区lue to have some default value without using some backing field?


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


If there's nothing behind it, it defaults to false, according to the documentation.

However, if you want it to be instantiated with an initial value other than false, you can do that this way:

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

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

    public Whatever()
    { 
        Value = true;
    }
}


The default value right now is false. To make it true, set it in the constructor.

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


By default Value would be false but it can be initialized in the constructor.


You can not set Value to any other default value than the default value of the datatype itself at the property. You need to assign the default value in the constructor of Whatever.


You can set a default value in the constructor.

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

public bool Value { get; set; }

By the way - with automatic properties, you still have a backing field, it just gets generated for your by the compiler (syntactic sugar).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜