C# Custom getter/setter without private variable

前端 未结 3 755
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 12:01

I learned c# recently, so when I learned to write properties, I was taught to do it like this:

public string Name { get; set; }

Auto properties

3条回答
  •  悲哀的现实
    2021-02-01 12:36

    Properties don't need backing variables (fields) at all. While they can be used for encapsulating simple fields you can also use them to access other data.

    public Decimal GrandTotal { get { return FreightTotal + TaxTotal + LineTotal; } }
    

    or

    public string SomeStatus { get { return SomeMethodCall(); } }
    

    If the goal is to simply encapsulate some field with a property you would need some sort of backing field if you are not using automatic properties.

提交回复
热议问题