简体   繁体   中英

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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM