I was browsing some documentation for a physics library for XNA and noticed an example someone had used for creating a class for a Car.
This is a pretty simple example:
Class Car
{
private float gravity;
private float maxSpeed;
public Car(float gravity, float maxSpeed)
{
this.gravity = gravity;
this.maxSpeed = maxSpeed;
}
}
Now when i’ve created a constructor and set up the assigning of the passed in parameters I would do it this way:
Class Car
{
private float _gravity;
private float _maxSpeed;
public Car(float gravity, float maxSpeed)
{
_gravity = gravity;
_maxSpeed = maxSpeed;
}
}
Is there any advantage to either approach? I’ve only come across this a few times but I assume there’s a good reason for doing so, I’m just looking for the “best practice” way so to speak.
Thanks!
Both examples are functionally identical, and both methods are used by different people. It’s up to you which naming convention you go with. If you do give the field the same name as the parameter, then you will have to use
thisto access it.The important thing is to be consistent in your naming. I personally prefer to access fields with the
thiskeyword, but there are definitely a lot of people around here that like the underscore approach.Underscore:
If you prefix your private fields with an underscore, then you will always need to use that wherever you refer to it. It is clear (provided that you know the convention) that it is a private field, just from looking at it. Unfortunately, it is also very ugly, but that’s just my opinion.
No underscore:
If you do not prefix your private fields with an underscore, then you have the option of referring to it directly or via the
thiskeyword. This means that it possible to forget, and in your example you might assign the argument to itself:gravity = gravity;This should at least generate a warning, though. If you use the StyleCop tool, then it will by default enforce that you always access private fields through thethiskeyword.See these similar questions for more answers: