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

前端 未结 8 1250
借酒劲吻你
借酒劲吻你 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:38

    There is a difference. The first two are fields and the remainder are auto-properties.

    The second one, the compiler generates a private backing field and some boiler-plate get/set methods. These then allow you to access the properties like they were fields, but with the advantages only available to properties.

    It is always recommended to hide fields behind properties, by either making them private and writing your own property around it or using an auto-property.

    There's some advantages to properties. One being that properties can be made read-only, or even write-only, or read-only with an internal write-only, etc. Since they act just like methods, you can execute any arbitrary code inside of them. This is useful for when you need to implement things like INotifyPropertyChanged or if the property is actually calculated from several fields behind it.

    The other advantage is encapsulation. You aren't tying yourself directly to the fields of the class, but rather the property. So if some detail about the field changes (say it goes away and becomes calculated), by using the property you are insulating yourself from those implementation details.

    You should certainly look at using properties (for now adding the { get; set; }) for all cases. They are good practice in that they provide a level of encapsulation that shields the user from implementation specific details.

    0 讨论(0)
  • 2021-01-16 05:38

    You do not have to, but this just coding stundart, with its pros and cons. Consider this link for more resources:

    Property Acessors

    0 讨论(0)
提交回复
热议问题