Road = CarSimulation.NextSegment() ;CarSimulation is a reference to the Simulation Object that owns car. When car was constructed in the first line of Simulation.RunSimulation() by this code:
Car car = new Car( NextSegment(),this) ;the second parameter this refers to the object making this call, in this case the Simulation object. By storing this in the Car field CarSimulation in the constructor Car(), it gives the car object access to any of Simulations public properties and methods. Without this, the code to manage the car moving between road segments would have been much messier. In a future tutorial we'll see an even better way to do this using a C# feature called delegates.
The if statement following car.Travel() checks to see if the car is still travelling, and if it is and the simulation rolls a 6 on a dice then it alters the car speed up or down randomly by 10. This new speed is constrained to a minimum of 10 and a maximum of 70. The
rnd.Next(2)in this code
(Rnd.Next(2)*20)-10;returns a 0 or 1 so we get 0-10 or 20-10, ie -10 or 10.
Below is the main part of the program that runs when the program is loaded. We create a simulation object CarSimulation with 100 road segments then call RunSimulation().
static void Main(string[] args)The main part of any program- the bit that runs first is always in a static void Main function.
{
Simulation CarSimulation = new Simulation( 100 ) ;
CarSimulation.RunSimulation() ;
Console.ReadLine() ;
}
This isn't a very interesting simulation but it provides a reasonable demonstration in about 150 lines of code.
That completes this lesson. The next one will look at functions in detail as well as inheritance in object oriented programming.

