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

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

    In Version of C# (6.0) & greater, you can do :

    For Readonly properties

    public int ReadOnlyProp => 2;
    

    For both Writable & Readable properties

    public string PropTest { get; set; } = "test";
    

    In current Version of C# (7.0), you can do : (The snippet rather displays how you can use expression bodied get/set accessors to make is more compact when using with backing fields)

    private string label = "Default Value";
    
    // Expression-bodied get / set accessors.
    public string Label
    {
       get => label;
       set => this.label = value; 
     }
    

提交回复
热议问题