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

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

    In addition to the answer already accepted, for the scenario when you want to define a default property as a function of other properties you can use expression body notation on C#6.0 (and higher) for even more elegant and concise constructs like:

    public class Person{
    
        public string FullName  => $"{First} {Last}"; // expression body notation
    
        public string First { get; set; } = "First";
        public string Last { get; set; } = "Last";
    }
    

    You can use the above in the following fashion

        var p = new Person();
    
        p.FullName; // First Last
    
        p.First = "Jon";
        p.Last = "Snow";
    
        p.FullName; // Jon Snow
    

    In order to be able to use the above "=>" notation, the property must be read only, and you do not use the get accessor keyword.

    Details on MSDN

提交回复
热议问题