What is the best way to give a C# auto-property an initial value?

前端 未结 22 3288
死守一世寂寞
死守一世寂寞 2020-11-22 02:48

How do you give a C# auto-property an initial value?

I either use the constructor, or revert to the old syntax.

Using the Constructor:

22条回答
  •  一个人的身影
    2020-11-22 03:13

    Sometimes I use this, if I don't want it to be actually set and persisted in my db:

    class Person
    {
        private string _name; 
        public string Name 
        { 
            get 
            {
                return string.IsNullOrEmpty(_name) ? "Default Name" : _name;
            } 
    
            set { _name = value; } 
        }
    }
    

    Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to.

    Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving.

    Hope that helps!

提交回复
热议问题