I once told a friend of mine that programming is much like chess. In some cases it is; for example when you know where you want to get but there are so many paths to follow. Choosing between fields, properties and methods when you want to store a value temporarily or retrieve it, can be described as some of these scenarios. There was a time I created a class and wanted to store some data, but I was not sure which was the best way to do it. Should I create a simple private variable where I would store the value, use a property and some extra auxiliary variable, or instead avoid getters and setters and use nothing more than a method? Since there may be some developers out there sometimes confused with such questions, I thought of writing an article about it.
Is there a problem at all?
To get started, let's create a class called MartialArtist which holds a single important piece of information: the martial artist's name. Here's the code.
public class MartialArtist
{
//This is a field
public string Name;
//This is an automatic property
public string NameProp { get; set; }
//This is a simple method
public string GetName()
{
string name;
//Compute name
return name;
}
}
Ok, that's what we've been talking about. However things still don't seem to be complicated. There's a field, a property and a method and they all seem to work in their own way. So, let's make things a bit more complicated.
public class MartialArtist
{
//This is a field
public string Name;
public string _nameProp;
//This is a property
public string NameProp
{
get
{
return _nameProp;
}
set
{
_nameProp = value;
}
}
//This is a simple method
public string GetName()
{
return _nameProp;
}
}
Now, differences between them seem to get unclear. Why is a public field different from a public property using a private field? And what is the difference between a public property using a private field and a public method using a private field? Let's try to clear things out.
Fields vs Properties
Here's how we use the field.
MartialArtist BruceLee = new MartialArtist();
BruceLee.Name = "Bruce Lee";
string martialArtistName = BruceLee.Name;
And how about the property?
BruceLee.NameProp = "Bruce Lee";
string martialArtistName = BruceLee.NameProp;
There seems to be no difference between how we use a field or a property. So let's focus on what is a field and what makes a property.
A field is nothing more than a part of the class info. A position in the memory for a string variable to be placed. If we wish to store some value on Name, that's exactly where it will be stored. And if later on we wish to get it back that's where we'll get it from. That's as simple as it can get.
Properties are a bit more complicated. An automatic Name property looks like this
public string NameProp { get; set; }
This looks simple as well, however it is not. When we write this line, unaware to us, two methods and a field will automatically be created. These methods consist of the getter and the setter, and the variable represents the place where the data will be stored. In a few words, creating an automatic property will look like creating a non automatic property
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
True, an automatic property is nothing more than an actual property and the ability to create one was granted to us developers in order to save us the trouble of writing extra code than necessary. So, now that a few things concerning fields and properties are clearer, let's try and answer the base question. Should we prefer fields over properties?
Fields are, well, fields. Properties are methods that use fields. So properties are expected to be far slower in accessing stored values. However this is not what happens. You see, when creating properties with methods that keep it simple, these properties will be inlined by JIT compiler, so that they will be optimized and become faster; much faster. Even faster than a single field. So even if you guessed that you should choose a field over an automatic property, just because the field will execute faster, you should think about it twice.
Apart from being faster, using properties has more advantages. Properties may include extra code within their getter and setter methods and they may even include exception handling. They may also have no getter or setter method, this way averting the user from setting or getting the property's value directly.
Furthermore, you may not use a field as datasource for controls. You can instead use a property. Properties support encapsulation. Accessor methods can be overridden by classes inheriting this one. Also keep in mind that you may use properties on interfaces but you may not use fields.
One last thing to mention is you may think that you can create a field and, when needed, turn it into a property. Keep in mind in that case you will have to recompile all code that uses this field since a field is much different than a property, even though they use the same syntax when called. This may cause trouble to large projects.
True; there are not many good reasons to use a field over a parameter. There are some things, for example you may not use a parameter as a ref or out property when you call a method (but you may use a field for that reason) and you may not have a readonly parameter. However there are workarounds. You will not be forced to use fields, because of these things. Microsoft is little by little moving on to parameters and the basic reason fields are still being useful is because there are tons of code using them, as well as a lot of developers who are used to handling them.
Still, if you enjoy it, you are free to go on using fields the way like, as long as you keep in mind the things said.
Properties vs Methods
Let's move on to the methods. Again, what was that trouble we had?
public class MartialArtist
{
public string Name {get; set;}
private string _name;
public string GetName()
{
return _name;
}
}
Well, we were not sure when to use a property or a method. So far, we mentioned that some properties can get inlined, making them faster than using a method. However, this not the main difference.
Properties represent some info or attribute, while methods represent some action. For example Name is well suited to be a property since it represents a MartialArtist's value.
Since a property represents some object value, it is fairly expected that this value is easy to compute. It is a part of the object info after all. So a property is supposed to be fast. A method on the other hand could be expected to take a lot of time to complete.
int counterProperty = MartialArtists.Where(ma => ma.Origin == "Hong Kong").Count();
int counterMethod = MartialArtists.Where(ma => ma.GetOrigin() == "Hong Kong").Count();
Look at these expressions. Which one seems to be faster to you? The first one I guess. That's because you are expecting a property to work faster than a method. Actually, if you are not the person who has written the class code (most likely) you may not even realize if Origin is a property or a field. Anyway, in case a property takes a lot of time to compute every time it is called, you'd better go for the method.
Property values are expected to remain intact no matter how many times they are used. That's unless of course you change its value on purpose.
MartialArtist BruceLee = new MartialArtist();
string name1 = BruceLee.Name;
string name2 = BruceLee.Name;
name1 and name2 are expected to hold the same value. It's nothing more than a property of the object after all.
MartialArtist BruceLee = new MartialArtist();
string name1 = BruceLee.GetName();
string name2 = BruceLee.GetName();
In that case however name1 and name2 are far less obvious to hold the same value. Calling GetName once may have changed a lot of things, which will change what GetName will return the next time it is called.
Furthermore, properties should not have significant side effects. If for example, getting Name, will cause the NamePerSessionCounter to increase (which is a "significant" value supposed to increase only once per session), we might consider using a method instead to avoid confusion.
So, choosing between a property and a method depends on how you are planning to use it. Keep it simple so everyone is happy.
Getting close to the end of this article, let's talk about some well known property, DateTime.Now. This property behaves in the following way
public static DateTime Now { get; }
It does represent some info and no action, it is fast to get results and affects nothing more. So it's fair to be a property. What's strange about it, though, is that DateTime may not return the same value if called more than once (if it takes some time between the first and the second time for example), violating one of the things we told. So, if DateTime.Now returns different DateTime values each time it's called, should it be a property? This is the reason many people argue that DateTime.Now should have been turned into a static method instead.
Summary
You may use fields, properties and methods to get and set values within your code. Fields are not much better than properties. When comparing properties to methods, however, you should pay attention to what they are made for doing and how they affect the rest of your source code.