Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use an automatically implemented property instead of a field?

Tags:

c#

.net

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?

like image 933
Billy ONeal Avatar asked Jul 07 '10 20:07

Billy ONeal


2 Answers

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.

like image 96
driis Avatar answered Sep 26 '22 16:09

driis


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.

like image 40
SLaks Avatar answered Sep 23 '22 16:09

SLaks