Reputation: 106530
Between these two:
With Property:
class WithProperty
{
public string MyString {get; set;}
}
With Field:
class WithField
{
public string MyString;
}
Apparently I'm supposed to pick the first one. Why?
I've heard the argument that the point here is to allow interface changes, but if I have the second one, and change it to the first one, no other code should ever have to change. When recompiled everything's just going to point to the property instead.
Am I missing something important here?
Upvotes: 13
Views: 321
Reputation: 6514
The important part you are missing is the gravity of this statement:
When recompiled
When your code point to a field and you change it to point to a property of the same name, the C# itself doesn't change, but the resulting IL does - it generates a method call to the getter or setter as appropriate.
Not every app has all of it's pieces contained in a single distributed unit. Many apps rely on interfaces for pluggability/expandability. If you have an app with an interface to a field and you want to change it to a property to take advantage of the power of properties, the app has to be recompiled and redistributed. You might as well just make it a property in the first place.
Upvotes: 2
Reputation: 164281
The most important difference is the fact, that if you use a field, and later need to change it to a property (say, to enforce some validation), then all libraries calling your code will need to be recompiled. It's true that you can compile the exact same code if the name stays the same - but the consumers of your code will still need to be recompiled. This is because the IL generated to get the value is different between a field and a property. If it already is a property, you can make a change without forcing consumers of your code to change.
This may or may not be an issue for you. But the property is almost the same amount of code, and is considered best practice. I would always go for the property.
Upvotes: 19
Reputation: 69342
With a property, you can easily extend it to include new logic.
For example, if you need to add validation logic to the set
.
Upvotes: 0
Reputation: 887285
The property can be changed later if you need to add validation or other logic without breaking other assemblies.
Also, the property can be used with databinding.
Upvotes: 9