Difference in C# between different getter styles

前端 未结 3 1408
甜味超标
甜味超标 2020-12-05 01:55

I do sometimes see abbreviations in properties for the getter. E.g. those two types:

public int Number { get; } = 0

public int Number => 0;
3条回答
  •  旧时难觅i
    2020-12-05 02:10

    These are C# 6 language features.

    First example

    public int Number { get; } = 0
    

    The first example is a getter-only auto property. The backing field of a getter-only auto-property is implicitly declared as readonly.

    Second example

    public int Number => 0;
    

    And the second example is expression bodies on property-like function members. Note that there isn't any get keyword: It is implied by the use of the expression body syntax.

    Both are readonly.

提交回复
热议问题