Differences between Private Fields and Private Properties

后端 未结 6 1796
执笔经年
执笔经年 2020-12-15 15:33

What is the difference between using Private Properties instead of Private Fields

private String MyValue { get; set; }

// instead of

private String _myValu         


        
6条回答
  •  猫巷女王i
    2020-12-15 16:19

    The big gain you can get from a property (private, public, ...) is that it can produce a calculated value vs. a set value. For example

    class Person { 
      private DateTime _birthday;
      private int _age { get { return (DateTime.Now - _birthday).TotalYears; }
    }
    

    The advantage of this pattern is that only one value must be updated for N other values to reflect the change. This is true of properties regardless of accessibility. There is no specific advantage of a private property vs non-private property (other than it being private of course)

提交回复
热议问题