Set a default value to a property

后端 未结 5 1571
你的背包
你的背包 2021-02-11 21:58

Is it possible to set a default value without the body of a property? Preferably with annotations.

[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }
         


        
相关标签:
5条回答
  • 2021-02-11 22:18

    Old thread. Looks like Microsoft heard and this feature is available in .Net Framework 4.6+ (C# 6+) You can use it like

    public string MyValue { get; set; } = "My Default";
    
    0 讨论(0)
  • 2021-02-11 22:31

    If you are using C#5 and earlier, you have to do it in a constructor.

    but since C# 6.0, the ability to have auto property initializers is included, and the syntax is:

    public int myage { get; set; } = 33;
    
    0 讨论(0)
  • 2021-02-11 22:33

    In this very specific example, you sort of can:

    public bool IsFalse { get; set; }
    public bool IsTrue
    {
        get { return !IsFalse; }
        set { IsFalse = !value; }
    }
    
    public void Something()
    {
        var isTrue = this.IsTrue;
        var isFalse = this.IsFalse;
    }
    

    But, in general, no.

    0 讨论(0)
  • 2021-02-11 22:39

    Assign the default property value in the class constructor.

    class MyClass
    {
        public MyClass()
        {
            IsTrue = true;
            IsFalse = false;
        }
    
        public bool IsTrue { get; set; }
    
        public bool IsFalse { get; set; }
    
        [...]
    
        public void Something()
        {
            var isTrue = this.IsTrue;
            var isFalse = this.IsFalse;
        }
    }
    
    0 讨论(0)
  • 2021-02-11 22:41

    No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted to the constructor) to set the default values.

    If you have several overloads for your constructor, you may want to look at constructor chaining.

    Using C# 6+, you are able to do something like this...

    public string MyValue { get; set; } = "My Default";
    

    Oh, it gets more fun because people have even requested something like this...

    // this code won't compile!
    public string MyValue {
        private string _myValue;
        get { return _myValue ?? "My Default"; }
        set { _myValue = value; }
    }
    

    ... the advantage being that you could control the scope of the field to only be accesible in the property code so you don't have to worry about anything else in your class playing with the state without using the getter/setter.

    0 讨论(0)
提交回复
热议问题