Class C = new C( ) ;For instance this creates a new instance of class Simulation with the parameter 100.
Simulation CarSimulation = new Simulation( 100 ) ;
Scope and Destructors
One of the best things about .NET is that it does garbage collection for you. Unless you are using older unmanaged code, you do not have to worry about throwing away objects or memory leaks. C++ classes have a destructor and while it's possible to have one in C#, you rarely if ever need one. Probably nine out of ten C# developers will never have to write a destructor in their life. In a distant future tutorial I'll return to destructors but for now pretend I never mentioned them!
The Life of Variables
Variables, including objects exist as long as they are "in scope". If declared at the class level like topSpeed in RoadSegment then that variable exists until any instances of the class are no longer used. On the other hand, if declared local to a function, such as car in Simulation.RunSimulation() then car exists until the function is exited. There is also block scope, like the variable NewSpeed in Simulation.RunSimulation() ; This is created in the if blockif (Rnd.Next(...within the do loop. It exists until the } just before the while statement. You can create variables within blocks within blocks etc. Variables in the outer block are visible in the inner block but not the other way round.
{
int j=0;
{
int k = j+1; // This is ok
}
j=k; // Error - will not compile as k does not exist here any more
}
On the next page : The Car Sim Application and how it works

