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

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

    When you inline an initial value for a variable it will be done implicitly in the constructor anyway.

    I would argue that this syntax was best practice in C# up to 5:

    class Person 
    {
        public Person()
        {
            //do anything before variable assignment
    
            //assign initial values
            Name = "Default Name";
    
            //do anything after variable assignment
        }
        public string Name { get; set; }
    }
    

    As this gives you clear control of the order values are assigned.

    As of C#6 there is a new way:

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

提交回复
热议问题