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

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

    Starting with C# 6.0, We can assign default value to auto-implemented properties.

    public string Name { get; set; } = "Some Name";
    

    We can also create read-only auto implemented property like:

    public string Name { get; } = "Some Name";
    

    See: C# 6: First reactions , Initializers for automatically implemented properties - By Jon Skeet

提交回复
热议问题