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

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

    In C# 6 and above you can simply use the syntax:

    public object Foo { get; set; } = bar;
    

    Note that to have a readonly property simply omit the set, as so:

    public object Foo { get; } = bar;
    

    You can also assign readonly auto-properties from the constructor.

    Prior to this I responded as below.

    I'd avoid adding a default to the constructor; leave that for dynamic assignments and avoid having two points at which the variable is assigned (i.e. the type default and in the constructor). Typically I'd simply write a normal property in such cases.

    One other option is to do what ASP.Net does and define defaults via an attribute:

    http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

提交回复
热议问题