So far, your programs always print the same text. Things get interesting when a program remembers something, does math with it and reacts to what someone types. For that, you need variables.

Variables: labeled boxes

A variable is a storage spot with a name, like a labeled box. Your program puts a value into it. Later, it takes the value back out by its name, or puts a new one in.

C#
// variables.cs
string name = "Ada";
int age = 36;
Console.WriteLine(name);
Console.WriteLine(age);
age = 37;
Console.WriteLine(age);
Ada
36
37

In words, the line int age = 36; says: “Make a box named age for whole numbers and put 36 in it.” So in C#, the equals sign doesn’t mean “is equal to.” It means “put in.” The second-to-last line replaces the old value with 37. The name stays, the contents change: that’s why it’s called a “variable.”

Every variable has a type

The type comes before the name. It decides what kind of value fits in the box:

Type For Example
string text string city = "Chicago";
int whole numbers (up to about plus or minus two billion) int count = 12;
double numbers with a decimal point double length = 1.85;
bool true or false bool done = false;

In code, you always write decimals with a point, 1.85, whatever language your computer is set to. For amounts of money, C# has a type of its own that is more precise, decimal. It comes up in the follow-up course, K1.

The compiler makes sure that type and value go together. Text in a box for numbers is an error, and the program doesn’t start:

C#
// wrong-type.cs
int age = "thirty-six";
Console.WriteLine(age);

The compiler reports CS0029: it cannot convert the type string to int. That’s good news. The more mistakes the compiler finds, the fewer you run into only once the program is already running.

Names follow a few rules: they start with a letter, they contain no spaces, and upper and lower case count. By convention, variables start with a lowercase letter, and every further word starts with a capital: noteCount, lastInput. Accented letters would be allowed but are unusual; write cafe, not café. In this course, the names you choose are plain everyday words such as age, city or cups. C#’s own words are its keywords, such as string, int and if, and the names of .NET’s building blocks, such as Console. Whatever is neither is a name someone chose. Professional code uses English names too, so you build the habit from the start.

Putting text together

When a text starts with a dollar sign $, C# fills in values written in curly braces { }:

C#
// fill-in.cs
string name = "Ada";
int cups = 3;
Console.WriteLine($"{name} drank {cups} cups of tea today.");
Console.WriteLine("Without the dollar sign, it stays {name}.");
Ada drank 3 cups of tea today.
Without the dollar sign, it stays {name}.

The braces can also hold a calculation, for example {cups * 2}.

Doing math

C# does math with +, -, * (times) and / (divided by). Multiplication and division come before addition and subtraction, and parentheses come first of all. On top of that, there is %, the remainder of a division:

C#
// math.cs
int a = 17;
int b = 5;
Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
Console.WriteLine((a + b) * 2);
double c = 17;
Console.WriteLine(c / b);
22
12
85
3
2
44
3.4

Two lines deserve a second look:

  • 17 / 5 gives 3, not 3.4. When both numbers are whole numbers (int), the result is a whole number too, and the remainder is dropped. 17 % 5 gives you the remainder: 2. This integer division catches almost everyone off guard once. But it is often exactly what you need, for example to split 135 minutes into 2 hours and 15 minutes.
  • c / b gives 3.4 because c is a double. A computer set to another language, German for example, may show 3,4 with a comma instead: how a decimal number is printed depends on the computer’s language setting.

Reading input

Console.ReadLine() waits until someone types a line and presses Enter, and returns that line as a string:

C#
// greeting.cs
Console.Write("What is your name? ");
string name = Console.ReadLine() ?? "";
Console.WriteLine($"Hello, {name}!");
What is your name? Ada
Hello, Ada!

Now for the ?? "" you already know from lesson 1. Instead of a text, Console.ReadLine() can also return nothing at all, which C# calls null. That happens when no more input can come, for example because someone ended the input with Ctrl+Z and Enter (Windows) or with Ctrl+D (macOS, Linux). The compiler knows this and warns you if you skip that case. ?? "" means: “If nothing comes, use an empty text.” That way, name always holds a text, and the warning goes away.

Turning text into a number

Input is always text, even when someone types digits. C# doesn’t do math with text; it glues the pieces together:

C#
// text-is-not-a-number.cs
string input = "36";
Console.WriteLine(input + 1);
int age = int.Parse(input);
Console.WriteLine(age + 1);
361
37

input + 1 sticks the 1 onto the end of the text “36”. Only int.Parse turns the text “36” into the number 36, which you can do math with. Here is how that looks with real input:

C#
// next-year.cs
Console.Write("How old are you? ");
string input = Console.ReadLine() ?? "";
int age = int.Parse(input);
Console.WriteLine($"Next year you will be {age + 1}.");
How old are you? 36
Next year you will be 37.

Try what happens when you type “thirty-six.” The program stops with a long message that begins like this:

How old are you? thirty-six
Unhandled exception. System.FormatException: The input string 'thirty-six' was not in a correct format.

int.Parse couldn’t make a number out of the text. An exception like this ends the program, and the exit code is not 0. In the next lesson, you learn how to check the input first instead of letting the program crash.

Exercise 1

Write a program where-you-live.cs that asks for a name, then asks where the person lives, and then prints a sentence such as “Ada lives in Chicago.”

Solution 1

C#
// where-you-live.cs
Console.Write("What is your name? ");
string name = Console.ReadLine() ?? "";
Console.Write("Where do you live? ");
string place = Console.ReadLine() ?? "";
Console.WriteLine($"{name} lives in {place}.");
What is your name? Ada
Where do you live? Chicago
Ada lives in Chicago.

Exercise 2

Write a program minutes.cs. It asks for a number of minutes and prints it as hours and minutes. For 135, it should say: 135 minutes is 2 hours and 15 minutes. Tip: an hour has 60 minutes, and you now know / and %.

Solution 2

C#
// minutes.cs
Console.Write("How many minutes? ");
int minutes = int.Parse(Console.ReadLine() ?? "");
int hours = minutes / 60;
int remainder = minutes % 60;
Console.WriteLine($"{minutes} minutes is {hours} hours and {remainder} minutes.");
How many minutes? 135
135 minutes is 2 hours and 15 minutes.

135 / 60 gives 2 because the remainder is dropped, and 135 % 60 is exactly that remainder, 15. Here the input is read and turned into a number in a single line. It does the same as the two lines in next-year.cs that read the input and convert it, just shorter.

Exercise 3

Predict what this program prints before you run it. Write your prediction down, then compare.

C#
// prediction.cs
int x = 7;
int y = 2;
Console.WriteLine(x / y);
Console.WriteLine(x % y);
Console.WriteLine($"{x} + {y} = {x + y}");
Console.WriteLine("x + y");
x = x + y;
Console.WriteLine(x);

Solution 3

3
1
7 + 2 = 9
x + y
9

As integer division, 7 / 2 is 3, and the remainder is 1. In the third line, the dollar sign fills in the values and the result. The fourth line has no dollar sign, and inside quotation marks, x + y is just text. x = x + y looks like a wrong equation, but it means: “Work out x plus y and put the result in x.” After that, x holds 9.

What you can do now

  • You create variables, give them a type and change their value.
  • You tell string, int, double and bool apart.
  • You fill values into text with $"…{…}".
  • You do math with whole numbers and know that / cuts off the remainder and % gives it to you.
  • You read input with Console.ReadLine() ?? "" and turn it into numbers with int.Parse.

Read more