In this chapter, you will learn all about variables. A variable is a named place in the computer’s memory where a program can store something. It can be anything you want. In fact, you can have as many variables in your program as you need.

This chapter will start with some simple examples, but eventually you will see that variables are absolutely fundamental to programming.

Storing Text

The first task will introduce you to variables. You will learn how to perform some basic operations with them.

Task

You’ll create a variable named message. Afterward, you will store some text in it. Finally, you will display the value of the variable to the user.

Solution

Here is the code:

static void Main(string[] args) {     // Declaration of a variable to store text     string message;     // Storing a value in prepared variable (assignment statement)     message = "I can't live with you.";     // Another variable (initialized with some value)     string anotherMessage = "I can't live without you.";     // Output of variables     Console.WriteLine(message);     Console.WriteLine(anotherMessage);     // Waiting for Enter     Console.ReadLine(); }

Discussion

Now let’s discuss the solution .

Variable Declaration

If you want to use a variable, you need to declare (create) it first.

The general syntax of a variable declaration statement is as follows: typeName[space]variableName[semicolon].

In this case, it reads as follows:

string message;

The type denotes the category of values that you want to store in the variable. In this case, you want to store text, which is why you used the type called string.

Alternative

There is an alternative way to write a variable declaration statement. In front of the semicolon, you can use an equal sign and the initial value of the variable.

Here is an example of this syntax:

string anotherMessage = "I can't live without you.";

Assignment Statement

There is one more thing in the code that needs to be explained. The second statement is as follows:

message = "I can't live with you.";

This stores a value (the text “I can’t live with you.”) in the prepared variable (message), and it is called an assignment statement. You use it whenever you want to store something.

The general syntax of the assignment statement is as follows:

  • WHERE (TO STORE) = WHAT (TO STORE);

Storing Numbers

In the next task, you will learn about variables that store numbers rather than text.

Task

You will create (declare) a variable called number. Afterward, you will store some number in it. Finally, you will display the variable’s value to the user.

Solution

The data type for numeric values is called int. Strictly speaking, this is the data type for whole numbers (integers). It will not be long until you see that distinguishing whole and decimal numbers matters in programming.

static void Main(string[] args) {     // Variable for storing number (with initial value)     int number = -12;     // Output of value of the variable     Console.WriteLine("Value of the variable: " + number);     // Waiting for Enter     Console.ReadLine(); }

Do not forget, numbers are entered without quotes.

Adding 1 and 1

What? Adding 1 and 1 again? You probably think I’m going mad!

Task

In the previous chapter, I told you that variables could provide you with greater certainty when combining numbers with text. Now I am returning to that suggestion.

Solution

Here is the code:

      static void Main(string[] args)         {             // Precalculation of result (into a variable)             int sum = 1 + 1;             // Output to the user             Console.WriteLine( @"Answer to Senior math test ========================= One and one is: " + sum);             // Waiting for Enter             Console.ReadLine();         }     }

For the result of running the program, see Figure 4-1.

Figure 4-1
figure 1

The result of the 1 plus 1 program

Discussion

Please compare the calculation of adding 1 to 1 to the calculations from the previous chapter. Here you explicitly store the result in a variable. This allows you to avoid possible problems with the order of evaluation and getting the incorrect answer of 11.

Doing Calculations with Variables

In the next task, you will learn how to use several variables at once.

Task

You are going to store some numbers in two variables. After that, you will calculate their sum into the third one.

Solution

Here is the code:

static void Main(string[] args) {     // 1. SOLUTION     // Values to be summed     int firstNumber = 42;     int secondNumber = 11;     // Calculating     int sum = firstNumber + secondNumber;     // Output     Console.WriteLine("Sum is: " + sum);     // 2. SOLUTION     // Declaring all variables at once     int thirdNumber, fourthNumber, newSum;     // Values to be summed     thirdNumber = 42;     fourthNumber = 11;     // Calculating     newSum = thirdNumber + fourthNumber;     // Output     Console.WriteLine("Calculated another way: " + newSum);     // Waiting for Enter     Console.ReadLine(); }

Discussion

The two (alternative) solutions show two cases you will often meet.

  • You declare a variable and immediately store a value in it.

  • You declare a variable first and store a value in it later.

Assembling a Grand Combination

Often you need to assemble your output from several values. In this task, you will learn how.

Task

I will show you how to assemble complex text via an example of a soccer match result (Figure 4-2).

Figure 4-2
figure 2

Grand combination program

In the example, you have some fixed text, some (potentially) variable text, and some (potentially) variable numbers. This is a typical real-world situation.

Solution

To store (potentially) variable values, you use variables. Of course, the values are actually fixed in this simple program, but generally you would be getting them from somewhere else (such as a user, file, database, or web service). You will learn later in the book how to get input from a user.

static void Main(string[] args) {     // Data in variables     string club1 = "FC Liverpool";     string club2 = "Manchester United";     int goals1 = 3;     int goals2 = 2;     // Output of match result     Console.WriteLine(         "Match " + club1 + " - " + club2 +         " ended with result " +         goals1 + ":" + goals2 + ".");     // Waiting for Enter     Console.ReadLine(); }

Discussion

In the solution, you should especially note the following:

  • You are using variables with different data types to store different kinds of values.

  • You are constructing the displayed message from nine parts joined together by eigth plus signs. Some of the parts of the message are fixed, while the others are variable.

Working with Decimal Numbers

In programming, you need to thoroughly distinguish between whole and decimal numbers. You already know how to work with whole numbers, so now you will look at the decimals.

Task

In this task, I will show you some examples of how to work with decimals.

Solution

In C#, there is a type called double for decimal numbers. Here is the code:

static void Main(string[] args) {     // IN CODE, decimal separator is always DOT regardless of computer language settings     double piApproximately = 3.14;     // Pi is already available in C#     double piMorePrecisely = Math.PI;     // Decimal numbers have always limited precision     double notCompletelyOne = 0.999999999999999999;     // Outputs     Console.WriteLine("Pi value from our code: " + piApproximately);     Console.WriteLine("Pi value from C#: " + piMorePrecisely);     Console.WriteLine("This should not be exact one: " + notCompletelyOne);     // Waiting for Enter     Console.ReadLine(); }

Discussion

Please note the following:

  • In code, you always need to use a decimal point as a separator between the integer and decimal parts of a number .

  • However, the output depends on your Windows settings. As you can see in Figure 4-3, the output on my computer uses a comma as a decimal separator since I have my computer set to the Czech language.

  • You can also see that decimal numbers do not have infinite precision. They are rounded after approximately 15 significant digits.

Figure 4-3
figure 3

The result of the decimal numbers program

Working with Logical Values

In programming, you often work with logical values, which are the values of “yes” and “no.”

Task

In this task, I will show you how to work with logical values.

Solution

The type for logical values is called bool in C#. The value “yes” is written as true, and the value “no” is written as false. Here is the code:

static void Main(string[] args) {     // Two logical (Boolean) variables     bool thePrettiestGirlLovesMe = true;     bool iAmHungry = false;     // Use exclamation mark to negate logical value     bool iAmNotHungry = !iAmHungry;     // Output     Console.WriteLine("She loves me: " + thePrettiestGirlLovesMe);     Console.WriteLine("I am hungry: " + iAmHungry);     Console.WriteLine("I am not hungry: " + iAmNotHungry);     // Waiting for Enter     Console.ReadLine(); }

Discussion

Note that you use an exclamation mark whenever you need to negate a logical value (to flip it from “yes” to “no” and back again).

Summary

In this chapter, you were introduced to the important concept of variables. In every real program, you need to temporarily store values (calculation results, user inputs, etc.) in a computer’s memory, and this is exactly what you use variables for. A variable is a place in memory that has a name to reference it and its data type to be clear about what kind of data you will store in it.

Specifically, you learned the following:

  • Before you can use a variable, you must declare it. An appropriate statement is string message;.

  • To store a value in a variable, you use the assignment statement format of where = what;. An example is message = "Some text";.

  • In C#, the data type for text is string.

  • The data type for the whole numbers (integers) is int.

  • In programming, contrary to common usage, care must be taken to distinguish between whole and decimal numbers.

  • The data type for decimal numbers is double.

  • There is a special data type called bool for storing so-called logical values true and false, which are computer equivalents of “yes” and “no.”