There are situations where I declare member variables at the top of my class and then also declare a property to access or set that member variable, but I ask myself if the property is necessary if it variable is only going to be accessed and set from within the class and no where else, so what is the advantage of using a property to access and set a member variable instead of just doing it directly to the member variable itself. Here is an example:
public class Car
{
int speed; //Is this sufficient enough if Car will only set and get it.
public Car(int initialSpeed)
{
speed = initialSpeed;
}
//Is this actually necessary, is it only for setting and getting the member
//variable or does it add some benefit to it, such as caching and if so,
//how does caching work with properties.
public int Speed
{
get{return speed;}
set{speed = value;}
}
//Which is better?
public void MultiplySpeed(int multiply)
{
speed = speed * multiply; //Line 1
this.Speed = this.Speed * multiply; //Line 2
//Change speed value many times
speed = speed + speed + speed;
speed = speed * speed;
speed = speed / 3;
speed = speed - 4;
}
}
In the above, if I don't have the property Speed to set and get the variable speed, and I decide to change int speed to int spd, I will have to change speed to spd everywhere it is used, however, if I use a property such as Speed to set and get speed, I will just have to change speed to spd in the get and set of the property, so in my MutilplySpeed method, stuff like above this.Speed = this.Speed + this.Speed + this.Speed will not break.
I agree with Frederik's answer. One thing that makes it slightly less work to follow his advice is to use automatic properties. Those are just properties that automatically generate the standard getter/setter logic. You don't get any validation, but you can always replace the automatic property with a standard one later. This replacement is not a breaking change.
Here I've replaced the Speed property in your example with an automatic property. Notice that the member variable disappears and your class must access it through the property.
You can also use another flavour called "get with private set". This means that the getter is public, but the setter is private. You define it like this:
As for your question about the
this.
prefix, it's usually irrelevant. The only time it matters is when you've defined a method parameter or local variable with the same name as a member variable. Then you can usethis
to access the member variable.Things like validation can be covered at one place. The member is encapsulated, and you want have to worry about validation and other things from the rest of your class.
In your current scenario it doesn't really make a difference, but when you need to change the variable or need to add behavior, it's easier when you use properties, because you only have one place where you need to change it.
If the variable is
private
, I will often not create a property for it. If it is, in any way, exposed outside the type, I always expose it through a property for different reasons:Also, if the field is exposed through a property, I always access it through the property, even within the class.
Update
In response to your updated code samples: there are a number of things to consider around the code design here.
One typical piece of advice (that I find very good) is "write for clarity, test for performance". That means that when you write your code, your first concern should be whether it is clear what the code does when looking at it. This is often (but not always) more important than the raw speed of the code. Write speed optimizations when you have established where you gain it. Accessing a property will be a tad slower than reading the field directly, but in most cases, the difference will be negligible (if at all measurable).
Atomicity may be an issue. Given your code sample, we have the field
speed
, that is publicly exposed through the propertySpeed
. If the methodMultiplySpeed
needs to perform several updates to the value, those intermediate values will be available through theSpeed
property at different times while the calculation is ongoing. This is true regardless of whether you update the field directly or through the property. In cases like this it is perhaps better to first put the value into a local variable, use that for the calculations and assign the value of that variable back to the property when done.Lastly, other side effects. It could be that changing the value of
Speed
should raise an event (such asSpeedChanged
). In cases like that, it is also probably a good idea not to make the update until the calculation is done.I like to think about the property as a contract and the field as implementation. Anybody (except for the core of my type) that needs the value should use the contract. Relying on the implementation should be done only if there are good reasons to bypass the contract.
And yes, if you encapsulate the access to the field in the property, naturally changing the name of the field will require less updates (and perhaps also the name of the field becomes less important).
I hope that makes sense, and is not too much off topic ;)
The only genuine reason I know of is if the field is being accessed from outside of the assembly. In that case, should you want to add light functionality to that field (maybe set a Dirty flag or validate a change) you have to change it to a property which changes the way it is viewed by the calling assembly, which will also need rebuilding. In very rare cases, you might find that you don't have control over that assembly, then you have a problem.
Don't let the OO zealots tell you that it's philsophically wrong to use public fields, although I might agree that auto-properties make the argument somewhat moot.
The fact is, there is not a lot of difference between a publicly declared field and a public property with a private backing store if there is no extra logic. That being said, it is still considered best practice to use properties.
And before everybody jumps on me about extensibility, remember that if you do later need to add functionality, you can keep the name with the property and introduce a new name for the backing store so it's not a breaking change.
In my opinion the language design is broken. There should not be two ways of doing things that have so much semantic overlap. Properties/Fields should have seamlessly provided the benefits of eaither approach depending on how they are used. If the program makes minimal use of Property features they should act the same way as fields. There should furthermore not be a need to declare empty get; and set; methods in this case. The differences strike me as artificial.
It's a great language; and pretty clean for the most part. That doesn't mean it shouldn't be improved upon "next time".