1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - An Object Oriented Approach to Programming

By David Bolton, About.com

9 of 10

More About the Car Simulation

The next NextSegment() method fetches road segments one by one. As the Roads ArrayList items can be any type we have to tell the compiler to cast any indexed object as a RoadSegment and the as keyword does this. If it fails, the expression returns null. It deliberately does not generate exceptions. There is a related keyword is that returns true if the object is of a specified type.

Moving the Car

As this is a console application, it uses System.Console.WriteLine() to output messages. Where there are one or more parameters printed out the positions of those parameters in the list is indicated by {position} eg {0}, {1} etc. The syntax is like this:

Console.WriteLine( Message_String, parameter 0, Parameter 1, Parameter 2....) ;
Where {0} in Message_string is replaced by parameter 0, {1} by parameter 1 etc.

IsTravelling is a property of the Car class. By using a verb for this, it makes the while loop read like While car is Travelling. While this is true, the program loops round and round calling car.Travel() and the if statement after it. Every time the car travels we check to see if it has reached the end of the last segment. At that point istravelling is set false. The current speed is added to the Car.RoadPos field. If this takes the car past the end of this road segment then if this was the last road segment, the journey ends. Otherwise it works out how far the car moved into the next road segment, fetches the next road segment and carries on.

Shortcut Maths

The Car.Travel() method uses both += and -= assignment short cuts. If you know C, or C++ you'll recognise these, a += b means add b to a (and store the result in a). There are short cuts for subtraction, multiplication, division and various logical functions. We'll come back to these in a future lesson.

On the next page : Finishing the Lesson

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. More About the Car Simulation

©2009 About.com, a part of The New York Times Company.

All rights reserved.