I am doing an exercise on making a small console program which shows how fast a car is moving and a function to make it go either faster or slower.
So here is my class called car, it contains a constructor.
There is a get and set accessor for the private int speed.
There are 2 methods called accelerate and break.
class car
{
private int speed;
public car (int initialSpeed) //initializes car speed
{
Speed = initialSpeed;
}
public void accelerate() //increase Speed
{
Speed = Speed + 10;
}
public void brake() //decrease Speed
{
Speed = Speed - 10;
}
public int Speed //access private int speed
{
get { return speed; }
set { speed = Speed; }
}
}
Now here is the problem:
class program
{
static void Main(string[] args)
{
var Car = new car(5);
Console.WriteLine(Car.Speed);
}
}
When I run the program the console just displays 0 even though initialized with 5. Why is this happening and what am I doing wrong?
Your Speed
property is the problem. Here's the code:
public int Speed //access private int speed
{
get { return speed; }
set { speed = Speed; }
}
The getter is fine - it returns the value of the private variable.
The setter, however, sets the value of variable to the result of evaluating the getter - ignoring the value passed into the setter entirely (available via the value
variable). It should be:
public int Speed
{
get { return speed; }
set { speed = value; }
}
Or better yet, use an automatically implemented property - remove the speed
field, and just have:
public int Speed { get; set; }
At the same time, I'd suggest learning about compound assignment operators and .NET naming conventions. If you're using C# 6 you can also use expression-bodied members, leaving a really small amount of code:
class Car
{
public int Speed { get; set; }
public Car(int initialSpeed)
{
Speed = initialSpeed;
}
public void Accelerate() => Speed += 10;
public void Brake() => Speed -= 10;
}
See more on this question at Stackoverflow