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.