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

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

    In C# 6.0 this is a breeze!

    You can do it in the Class declaration itself, in the property declaration statements.

    public class Coordinate
    { 
        public int X { get; set; } = 34; // get or set auto-property with initializer
    
        public int Y { get; } = 89;      // read-only auto-property with initializer
    
        public int Z { get; }            // read-only auto-property with no initializer
                                         // so it has to be initialized from constructor    
    
        public Coordinate()              // .ctor()
        {
            Z = 42;
        }
    }
    

提交回复
热议问题