O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variables

C# methods can have named places to hold information. These are called variables, because the information they contain may be different each time the program runs, or your code may change a variable while the program runs. Example 2-5 defines three variables in our program’s Main method, to represent the distance traveled by the car, how long it has been moving, and how much fuel it has consumed so far. These variables don’t vary at all in this example—a variable’s value can change, but it’s OK to create variables whose value is fixed.

Example 2-5. Variables

static void Main(string[] args)
{
    double kmTravelled = 5.14;
    double elapsedSeconds = 78.74;
    double fuelKilosConsumed = 2.7;
}

Notice that the variable names (kmTravelled, elapsedSeconds, and fuelKilosConsumed) are reasonably descriptive. In algebra it’s common to use single letters as variable names, but in code it is a good practice to use names that make it clear what the variable holds.

Warning

If you can’t think of a good descriptive name for a variable, that’s often a symptom of trouble. It’s hard to write code that works if it’s not clear what information the code is working with.

These names indicate not just what the variables represent, but also their units. This is of no significance to the compiler—we could call the three variables tom, dick, and harry for all it cares—but it’s useful for humans looking at the code. Misunderstandings about whether a particular value is in metric or imperial units have been known ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required