简体   繁体   中英

What's the reason for peoples to use properties with get; set; instead of fields?

I often see properties in classes, instead of fields. It looks like that:

class TestClass
{
    public ulong Id { get; set; }
    public string Description { get; set; }
}

Why peoples do this? They could use fields instead. I see at least single pro there - we can pass fields with ref keyword into functions. Is there any pro for properties or other reasons to use them like that ?

The main reason is encapsulation - the value can only be changed trough the corresponding properties, and this continues to be the case even if you later decide that the property shouldn't just return a value. Maybe you find that you'll want to fire an event when a value changes? If you've got a property, that's very easy. If you've got a public field, you need to make a breaking change.

In addition, properties can be virtual or declared in interfaces. And they can be declared read-only.

Oh, and it helps in debugging: You can set a breakpoint on the "set", if you want to know who is changing your value (unexpectedly).

People use properties instead of fields mainly due to coding conventions. If it doesn't perform any actual encapsulation (in case of POCO), then there's not much of a difference in C#. Most of the times fields could be used instead of properties with no consequences whatsoever.

// This:
public string MyValue;
// Could be later on changed to this:
public string MyValue { get; set; }
// With no compatibility issues.

Although it's interesting to speculate why conventions are the way they are. In C# difference between properties and fields is mostly hidden from consumer standpoint. This is not necessarily the case in older languages. Ie in Java you had to write getter and setter methods explicitly. So if you have a field in Java, and now you decide that you want to encapsulate it, then you would need to go over all usages of that field and use getters and setters instead. This could be even a bigger issue if you use dynamic library linking (that used to be popular style of deployment some time ago). Because of this it was easier to encapsulate fields from the start, so you wouldn't have backwards compatibility issues in the future. Naturally these conventions spread to other languages as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM