In the last chapter you wrote string name = "Lesther"; and I promised we’d go through it slowly. That line is a variable, and almost everything a program does goes through variables: storing a value, changing it, doing math with it and showing the result.
By the end of this chapter you’ll know how to store text, numbers and yes-or-no answers, do arithmetic with them and ask the person using your program for input. With that you’ll build a tip calculator.
For each example, create a project with dotnet new console, replace everything in Program.cs with the code and run it with dotnet run, just like in chapter 1.
What a variable is
A variable is a named place where you store a value. Think of a box with a label: the label is the name, and the value is inside.
string name = "Maria";
int age = 30;
Console.WriteLine(name);
Console.WriteLine(age);
Maria
30
Each declaration has three parts. First the type (string, int), which says what kind of value fits in the box. Then the name (name, age). Last, the = and the value you store. In C#, = doesn’t mean “is equal to” like in math class. It means “store this here”.
Notice that Console.WriteLine(name) has no quotes. With quotes it would print the word “name”. Without them, C# looks up the variable and prints what’s inside.
Changing the value
A variable can change, which is why it’s called that. Once it’s declared, you assign a new value without repeating the type:
int points = 10;
Console.WriteLine(points);
points = 15;
Console.WriteLine(points);
points = points + 5;
Console.WriteLine(points);
points += 5;
Console.WriteLine(points);
10
15
20
25
Read points = points + 5 from right to left: take the current value of points, add 5 and store the result in points. points += 5 does the same thing with less typing.
The types you’ll use all the time
C# wants to know what type of value each variable holds. These six cover almost everything at the start:
string city = "Ponce";
int cupsOfCoffee = 3;
double temperature = 31.5;
decimal price = 4.75m;
bool isOpen = true;
char initial = 'P';
Console.WriteLine(city);
Console.WriteLine(cupsOfCoffee);
Console.WriteLine(temperature);
Console.WriteLine(price);
Console.WriteLine(isOpen);
Console.WriteLine(initial);
Ponce
3
31.5
4.75
True
P
string: text, in double quotes.int: whole numbers, no decimals. Positive or negative.double: numbers with decimals, for measurements like temperature or distance.decimal: numbers with decimals, for money. The value ends with anm.bool: can only betrueorfalse. It prints with a capital letter,True.char: a single character, in single quotes.
If your computer is set up to use a comma for decimals, you’ll see 31,5 and 4,75. It’s the same number; C# prints it using your system’s format.
Why money goes in decimal
double and decimal look like they do the same job, but they don’t store numbers the same way. Look at this:
double a = 0.1 + 0.2;
decimal b = 0.1m + 0.2m;
Console.WriteLine(a);
Console.WriteLine(b);
0.30000000000000004
0.3
double stores numbers in a format that’s very fast but can’t represent some decimals, like 0.1, exactly. The difference is tiny, but when you add up thousands of prices it builds up and the cents stop matching. decimal stores decimals exactly. My rule is simple: if it’s money, use decimal. For everything else with decimals, double is fine.
The type protects your data
Once you declare a variable with a type, it only accepts values of that type. If you write this:
int age = "thirty";
the program doesn’t compile:
.../Program.cs(1,11): error CS0029: Cannot implicitly convert type 'string' to 'int'
The message says it can’t turn a string into an int. It may feel strict, but it helps you: the compiler finds the mistake before the program runs, not when someone is already using it.
var: let C# figure out the type
Writing the type every time gets repetitive. With var, C# looks at the value on the right and picks the type for you:
var name = "Maria";
var age = 30;
var price = 4.75m;
Console.WriteLine($"{name}, {age}, {price}");
Maria, 30, 4.75
name is still a string, age is still an int and price is still a decimal. var doesn’t create a variable without a type: C# decides the type when it compiles, and it doesn’t change after that. If you later try age = "thirty";, you get the same error as before.
So when should you write the type? Use var when the type is obvious from the line itself. Write it when it isn’t, or when the value could fool you. For example, var total = 10; creates an int, even if you were thinking about money. If you want a decimal, write decimal total = 10;. While you’re learning, writing the type makes you think about what you’re storing, so in this path I’ll write it out most of the time.
How to name your variables
In C#, variables are written in camelCase: the first word in lowercase and every word after it starting with a capital letter, all joined together. name, age, cupsOfCoffee, discountedPrice.
A few rules the compiler enforces:
- No spaces.
- They can’t start with a number.
1namedoesn’t work;name1does. - Case matters.
ageandAgeare two different variables.
And one it doesn’t enforce, but that matters more: use names that say what they hold. x or data tell you nothing when you come back to the code a week later. discountedPrice tells you everything.
Interpolation: putting variables inside text
You already used it in chapter 1. When you put $ before the quotes, anything inside curly braces {} is replaced by its value:
string name = "Maria";
int age = 30;
Console.WriteLine($"{name} is {age} years old.");
Console.WriteLine($"Next year she'll be {age + 1}.");
Maria is 30 years old.
Next year she'll be 31.
You can put a calculation inside the braces, like age + 1, and C# writes the result. If you forget the $, you’ll see the braces and the names printed as they are.
Doing math
C# has the operations you already know, plus one more:
int a = 7;
int b = 2;
Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
9
5
14
3
1
* is multiplication and / is division. % gives you the remainder of a division: 7 divided by 2 is 3 with 1 left over. It looks odd at first, but it’s useful for things like checking whether a number is even (the remainder when dividing by 2 is 0). You’ll use it once your program starts making decisions.
Just like in math, * and / come before + and -. 2 + 3 * 4 is 14. If you want a different order, use parentheses: (2 + 3) * 4 is 20.
The division surprise
Did you notice that 7 / 2 gave 3 and not 3.5? It’s not a bug. When you divide two int values, the result is also an int, and C# drops the decimal part. It doesn’t round: it cuts it off.
This trips up everyone, especially because storing the result in a double doesn’t fix it:
double wrong = 7 / 2;
double right = 7.0 / 2;
Console.WriteLine(wrong);
Console.WriteLine(right);
3
3.5
For wrong, C# first divides 7 / 2 as whole numbers, gets 3, and only then stores it in the double. By then it’s too late. For right, 7.0 has a decimal point, so the division uses decimals from the start. The rule: if you want decimals in the result, at least one of the numbers in the division needs to have them.
Reading what the user types
So far the values were written in the code. To ask the person using your program for them, you use Console.ReadLine():
Console.Write("What's your name? ");
var name = Console.ReadLine();
Console.WriteLine($"Hello, {name}");
What's your name? Maria
Hello, Maria
Console.Write is like WriteLine, but it doesn’t move to a new line, so what you type shows up next to the question. Console.ReadLine() waits for you to type something and press Enter, and gives you back what you typed.
Turning text into a number
ReadLine always gives you text, even if you type a number. To do math with it, you convert it with int.Parse:
Console.Write("How old are you? ");
var text = Console.ReadLine();
int age = int.Parse(text);
Console.WriteLine($"In ten years you'll be {age + 10}.");
How old are you? 30
In ten years you'll be 40.
There’s the same thing for numbers with decimals: decimal.Parse and double.Parse.
VS Code may underline text, and the build may show a warning that mentions null. That’s because, in rare cases, ReadLine can return nothing at all. It’s a warning, not an error: the program still runs.
What is a problem is typing something that isn’t a number. Run the program and type thirty:
Unhandled exception. System.FormatException: The input string 'thirty' was not in a correct format.
Several more lines follow, and the program stops. int.Parse trusts you to give it a number, and when you don’t, it fails. For now, type valid numbers when you test. In chapter 7 we learn how to read these messages and how to handle bad input without the program crashing.
Constants: values that don’t change
Some values should never change while the program runs. That’s what const is for:
const int MinutesPerHour = 60;
int hours = 3;
Console.WriteLine($"{hours} hours is {hours * MinutesPerHour} minutes.");
3 hours is 180 minutes.
If you later try MinutesPerHour = 61;, the compiler stops you with error CS0131. Constants are named in PascalCase, with the first letter capitalized too, to set them apart from variables. Using a named constant instead of typing 60 all over your code makes it clear what that number means, and if it ever changes, you change it in one place.
Exercise: tip calculator
Write a program that:
- Asks how much the bill was (with decimals, for example
45.50). - Asks what tip percentage you want to leave (a whole number, for example
18). - Asks how many people are splitting it.
- Shows the tip, the total and how much each person pays.
Think about which type to use for each value before you write any code. A hint for showing money: {total:F2} inside the interpolation prints the number with two decimals.
Try it before you look at the solution.
Suggested solution
Console.Write("How much was the bill? ");
var billText = Console.ReadLine();
decimal bill = decimal.Parse(billText);
Console.Write("What tip percentage will you leave? ");
var percentText = Console.ReadLine();
int percent = int.Parse(percentText);
Console.Write("How many people? ");
var peopleText = Console.ReadLine();
int people = int.Parse(peopleText);
decimal tip = bill * percent / 100;
decimal total = bill + tip;
decimal perPerson = total / people;
Console.WriteLine($"Tip: {tip:F2}");
Console.WriteLine($"Total: {total:F2}");
Console.WriteLine($"Each person pays: {perPerson:F2}");
How much was the bill? 45.50
What tip percentage will you leave? 18
How many people? 3
Tip: 8.19
Total: 53.69
Each person pays: 17.90
Notice three decisions. The bill is a decimal because it’s money. The percentage and the number of people are int because they’re whole numbers. And bill * percent / 100 doesn’t hit the division surprise, because bill is a decimal, which makes the whole calculation use decimals.
If your computer uses a comma for decimals, type the bill as 45,50. decimal.Parse follows your system’s format.
If your program doesn’t look like mine but gives the same result, that’s fine. There’s more than one correct way to write it.
What you learned
- A variable has a type, a name and a value, and you can change its value later.
string,int,double,decimal,boolandchar, and that money goes indecimal.varlets C# pick the type, but the type is still fixed.- Variables use camelCase and names that say what they hold.
- Interpolation with
$"..."puts values inside text. + - * / %, and that dividing twointvalues cuts off the decimals.Console.ReadLine()reads text andint.Parseturns it into a number, and it fails if the text isn’t a number.constfor values that don’t change.
In the next chapter your program starts making decisions: comparing values and doing one thing or another depending on the result.
Questions?
If something wasn’t clear or your calculator doesn’t give what you expected, send me a DM on Instagram or ask in the Discord community. Paste your code and what you got, and we’ll look at it.
