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

前端 未结 22 2997
死守一世寂寞
死守一世寂寞 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!

    0 讨论(0)
  • 2020-11-22 03:13

    Personally, I don't see the point of making it a property at all if you're not going to do anything at all beyond the auto-property. Just leave it as a field. The encapsulation benefit for these item are just red herrings, because there's nothing behind them to encapsulate. If you ever need to change the underlying implementation you're still free to refactor them as properties without breaking any dependent code.

    Hmm... maybe this will be the subject of it's own question later

    0 讨论(0)
  • 2020-11-22 03:15
    public Class ClassName{
        public int PropName{get;set;}
        public ClassName{
            PropName=0;  //Default Value
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:16

    little complete sample:

    using System.ComponentModel;
    
    private bool bShowGroup ;
    [Description("Show the group table"), Category("Sea"),DefaultValue(true)]
    public bool ShowGroup
    {
        get { return bShowGroup; }
        set { bShowGroup = value; }
    }
    
    0 讨论(0)
  • 2020-11-22 03:17
    class Person 
    {    
        /// Gets/sets a value indicating whether auto 
        /// save of review layer is enabled or not
        [System.ComponentModel.DefaultValue(true)] 
        public bool AutoSaveReviewLayer { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-22 03:18

    Have you tried using the DefaultValueAttribute or ShouldSerialize and Reset methods in conjunction with the constructor? I feel like one of these two methods is necessary if you're making a class that might show up on the designer surface or in a property grid.

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