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

前端 未结 22 3037
死守一世寂寞
死守一世寂寞 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:12

    I think this would do it for ya givng SomeFlag a default of false.

    private bool _SomeFlagSet = false;
    public bool SomeFlag
    {
        get
        {
            if (!_SomeFlagSet)
                SomeFlag = false;        
    
            return SomeFlag;
        }
        set
        {
            if (!_SomeFlagSet)
                _SomeFlagSet = true;
    
            SomeFlag = value;        
        }
    }
    

提交回复
热议问题