Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

前端 未结 8 1335
借酒劲吻你
借酒劲吻你 2021-01-16 04:59

I have been coding classes like this:

public class ReportViewModel
    {
        public string Status;
        public string DataSource;
        public Stri         


        
8条回答
  •  臣服心动
    2021-01-16 05:20

    At all depends on how this class will be used.

    If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).

    However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.

    If your class is going to be used by other assemblies then you should always convert public fields to properties.

    The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.

    Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.

提交回复
热议问题