Skip to content
wannacode

Variables and types

Problem

The price is in three places

In an online shop one price shows up in several places: in the catalog, in the cart and at checkout. If it is written as a number everywhere, here is what happens:

Console.WriteLine("Headphones: €49.90");
Console.WriteLine("In the cart: headphones, €49.90");
Console.WriteLine("To pay: €49.90");

Tomorrow the headphones are on sale. You have to find and fix every 49.90. Miss one, and the customer sees two different prices.

The idea

A variable: a name for a value

Write the price once and give it a name. Then write the name everywhere.

double price = 49.90;
Console.WriteLine("Headphones: €" + price);
Console.WriteLine("In the cart: headphones, €" + price);
Console.WriteLine("To pay: €" + price);
Output
Headphones: €49.9
In the cart: headphones, €49.9
To pay: €49.9

double price = 49.90; creates a variable: a place in memory with a name (price), a type (double, a decimal number) and a value (49.90). Wherever the code says price, the program takes the value from there.

+ between text and a value glues them into one text. That is why the spaces are inside the quotes.

The zero at the end disappeared: 49.90 came out as 49.9. For the number it is the same thing. You will see how to show the price with two digits after the decimal point in the lesson on input and output.

More precisely, if you are curious
  • A name starts with a letter and has no spaces. Write it in lowercase, and start each next word with a capital letter: price, pricePerNight. Uppercase and lowercase letters matter: price and Price are two different names.
  • The language also allows names with letters outside English (café), but do not do it. Code all over the world uses plain Latin names, and that is how your colleagues will write too.
  • A variable you have not given a value yet cannot be used. The compiler stops with an error.
  • If your computer prints 49,9 with a comma, those are Bulgarian (or other European) regional settings. C# follows them when it turns a number into text. The examples in this course use a point.

The idea

Kinds of values

The type says what the variable can hold. Here are the main ones:

string name = "Backpack";
double price = 39.90;
int stock = 12;
bool onSale = true;
char size = 'M';
Console.WriteLine(name + ", size " + size);
Console.WriteLine("Price: €" + price);
Console.WriteLine("In stock: " + stock + " items");
Console.WriteLine("On sale: " + onSale);
Output
Backpack, size M
Price: €39.9
In stock: 12 items
On sale: True
  • int: a whole number, for example a count.
  • double: a decimal number, for example a price or a weight. In code the decimal separator is a point: 39.90.
  • bool: yes or no, true or false.
  • char: one character, in single quotes: 'M'.
  • string: text, in double quotes: "Backpack". This is a string, a sequence of characters.

true in the code is printed as True. That is how C# turns boolean values into text.

More precisely, if you are curious

string is another name for System.String. The simple types (int, double, bool, char and so on) hold the value itself. string is a reference type: the variable holds a link to the text. The difference will matter in the "Classes and objects" module.

The numeric and other simple types in C#:

Type Size Values
byte 1 byte from 0 to 255 (unsigned)
sbyte 1 byte from -128 to 127
short 2 bytes from -32,768 to 32,767
ushort 2 bytes from 0 to 65,535 (unsigned)
int 4 bytes from -2,147,483,648 to 2,147,483,647
uint 4 bytes from 0 to 4,294,967,295 (unsigned)
long 8 bytes from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 8 bytes from 0 to 18,446,744,073,709,551,615 (unsigned)
float 4 bytes decimal, up to about ±3.4 · 10³⁸, about 6 to 9 significant digits
double 8 bytes decimal, up to about ±1.8 · 10³⁰⁸, about 15 to 17 significant digits
decimal 16 bytes decimal, up to about ±7.9 · 10²⁸, 28 to 29 significant digits, exact in base 10
char 2 bytes one Unicode character, codes from 0 to 65,535
bool 1 byte true or false

u in the name means unsigned: only zero and positive numbers. byte is unsigned without a u, and its signed version is sbyte. decimal is the type for money. double stores numbers in binary, and some decimal values like 0.1 do not come out exactly. Over a sum of thousands of payments, these small differences add up.

A number in code is an int or a double, unless you say otherwise. L at the end makes a number a long, f makes it a float, m makes it a decimal. Without m, the line decimal balance = 1250.75; does not compile. Underscores between digits only make it easier to read:

long population = 8_100_000_000L;
float weight = 1.5f;
decimal balance = 1250.75m;
Console.WriteLine(population + " " + weight + " " + balance);
Output
8100000000 1.5 1250.75

Try it

Find the bug

The program should print one purchase. It does not compile. Which line is the bug on?

Pick the line with the bug.

The idea

= stores a copy

The = sign is not "equals" as in math. It means: take the value on the right and store it in the variable on the left. This is called assignment. The variable's old value is gone.

When there is another variable on the right, a copy of its value at that moment is stored. The two variables do not stay connected:

int seats = 40;
int seatsAtStart = seats;
seats = 37;
Console.WriteLine("At the start: " + seatsAtStart);
Console.WriteLine("Now: " + seats);
Output
At the start: 40
Now: 37

seatsAtStart gets 40. Then seats becomes 37, but the copy in seatsAtStart stays 40.

Try it

Which value stays?

What will the program print?

int roomA = 12;
int roomB = 20;
roomA = roomB;
roomB = 25;
Console.WriteLine(roomA + " and " + roomB);
Answer

Problem

The sizes are swapped

A photo printing program gets the sizes swapped: width 120 and height 80, when they should be 80 x 120. It looks like you just need to store one in the other and back again:

int width = 120;
int height = 80;
width = height;
height = width;
Console.WriteLine(width + " x " + height);
Output
80 x 80

You got 80 x 80. Where did 120 go?

See it

Swapping with a helper variable

int width = 120;
int height = 80;
int temp = width;
width = height;
height = temp;
Console.WriteLine(width + " x " + height); // 80 x 120
Step by step, in words
  1. The width and the height were entered swapped: 120 and 80.
  2. temp = width: a copy of 120 goes into temp. width still holds 120.
  3. width = height: a copy of 80 goes into width. The old 120 is gone from there, but it is saved in temp.
  4. height = temp: 120 comes back from temp into height.
  5. They are swapped: 80 x 120.

In the naive version, width = height stores 80 in width, and the old 120 is gone. When height = width comes next, width already holds 80, and that is copied back.

The fix is a third, helper variable, temp. It keeps 120 before width is overwritten. Then 120 goes from temp into height, and the sizes come out 80 x 120.

Try it

Put the swap in order

At the shop, two coworkers trade shifts. morning is "Ivan", and evening is "Maria". Put the lines in order so they swap.

  1. morning = evening;
  2. Console.WriteLine("Morning: " + morning + ", evening: " + evening);
  3. string temp = morning;
  4. evening = temp;

The idea

var: the type is inferred

When the type is clear from the value, you can write var instead of it:

var city = "Plovdiv";
var nights = 3;
var pricePerNight = 65.0;
Console.WriteLine(city + ": " + nights + " nights at €" + pricePerNight);
Output
Plovdiv: 3 nights at €65

The compiler sees by itself that "Plovdiv" is text, 3 is an int and 65.0 is a double. This is called type inference.

var does not mean "no type". The type is decided by the first value, and after that it does not change:

var nights = 3;
nights = "three";
Message from the compiler
error CS0029: Cannot implicitly convert type 'string' to 'int'

In this course we will mostly write the type explicitly, so you can see it.

More precisely, if you are curious
  • var needs a value right away: var nights; does not compile, because there is no way to tell the type.
  • var is only for variables inside Main (and inside the other methods, which come in the "Methods" module).
  • C# also has dynamic: with it, the type is checked only while the program runs, not at compile time. It is rarely used, for data from other systems. We will not need it in this course.

Exercise

Your variables

Solve the tasks in your editor. The values are written in the code, with no reading from the keyboard. Reading is in the next lesson.

1. Swap. The top shelf has 15 books, the bottom one 27. Store them in two variables, swap their values and print before and after.

Output
Before: top 15, bottom 27
After: top 27, bottom 15

2. Age. Store a name and an age in two variables and print them in a sentence.

Output
Maria is 19 years old.

3. A hotel card. Store in variables the name of the hotel (text), the stars (a whole number), the rating (a decimal), whether there is breakfast (yes or no) and the category (one character). Print them.

Output
Hotel: Sea Star
Stars: 4
Rating: 8.7
Breakfast: True
Category: B

More tasks

  • Three in a circle. Three cash registers start the day with €120, €85 and €240. Move the amounts in a circle: the first goes into the second, the second into the third, the third into the first. Use one helper variable. Print 240 120 85.
  • The same with var. Rewrite task 3 with var everywhere. The output should not change.
  • An error on purpose. Store text in an int and a decimal number in an int. Read what the compiler says.

Test

Check yourself

1. What does the line int count = 5; do?
2. Which type is for a price like 12.99?
3. int a = 5; int b = a; a = 9; What is b?
4. Why does swapping two values need a third variable?
5. After var nights = 3;, what is true?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·