So far your programs do the same thing every time you run them. They store values, do some math and print the result, but they never choose anything. A real program does choose: if the password is wrong, it doesn’t let you in; if the cart is empty, it doesn’t charge you.
In this chapter your program learns to make decisions. First you’ll compare values, then you’ll use those comparisons with if and switch, and at the end you’ll read a number from the user without the program crashing when they type something else.
Comparing values
A decision starts with a question that has a yes or no answer. In C#, that answer is a bool: true or false. You know that type from the previous chapter. Comparison operators are what produce those values:
| Operator | Means |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
Try them. This is the full content of Program.cs:
int age = 20;
Console.WriteLine(age > 18);
Console.WriteLine(age == 18);
Console.WriteLine(age != 18);
True
False
True
Each line asks a question and C# answers. Is 20 greater than 18? Yes. Is 20 equal to 18? No. Is 20 different from 18? Yes.
Notice the == with two equals signs. A single = assigns a value, like when you write int age = 20;. Two == compare. Mixing them up is one of the most common mistakes when you start, and further down you’ll see what the compiler tells you when it happens.
You can also compare text with ==, but keep in mind the comparison is case-sensitive: "hello" == "Hello" is false.
if and else
if takes a condition in parentheses and, if it’s true, runs the block between the braces. else is what runs when the condition is false.
int age = 16;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are still a minor.");
}
You are still a minor.
Change 16 to 18, save and run again. Now you get the other line. The program is the same; the data changed, and the program took a different path.
The else is optional. If there’s nothing to do when the condition is false, leave it out.
The braces mark where each block starts and ends. If the block has a single line, C# lets you skip them, but I recommend always writing them. When you later add a second line, it’s very easy for it to end up outside the if without you noticing.
The single = mistake
Write if (age = 18) instead of if (age >= 18), save and run. The program doesn’t compile, and the message includes this:
error CS0029: Cannot implicitly convert type 'int' to 'bool'
With a single =, age = 18 is an assignment and its result is the number 18, not a yes or no. The if needs a bool, so the compiler stops you. When you see this error inside an if, look for an = that should have been ==.
More than two paths with else if
Sometimes there are more than two options. For that you chain conditions with else if:
int temperature = 31;
if (temperature >= 30)
{
Console.WriteLine("It's hot.");
}
else if (temperature >= 20)
{
Console.WriteLine("It's nice out.");
}
else
{
Console.WriteLine("It's cool.");
}
It's hot.
C# checks the conditions in order, top to bottom, and runs only the first block whose condition is true. Then it skips the rest. That’s why 31 says “It’s hot” and not “It’s nice out”, even though 31 is also greater than or equal to 20.
That means order matters. If you put temperature >= 20 first, you’ll never see “It’s hot”, because any temperature of 30 or more already matches the first condition. When your ranges overlap, start with the strictest one.
Combining conditions: &&, || and !
Many decisions depend on more than one thing. That’s what logical operators are for:
| Operator | Read as | Is true when |
|---|---|---|
&& | ”and” | both conditions are true |
|| | ”or” | at least one is true |
! | ”not” | the condition is false |
int age = 25;
bool hasTicket = true;
if (age >= 18 && hasTicket)
{
Console.WriteLine("You can get into the concert.");
}
string day = "saturday";
if (day == "saturday" || day == "sunday")
{
Console.WriteLine("It's the weekend.");
}
bool isRaining = false;
if (!isRaining)
{
Console.WriteLine("You don't need an umbrella.");
}
You can get into the concert.
It's the weekend.
You don't need an umbrella.
A few details that will save you headaches:
With ||, each side has to be a complete comparison. day == "saturday" || "sunday" doesn’t compile, because "sunday" on its own is just text, not a question.
A bool variable is already a condition. You don’t need to write if (hasTicket == true); if (hasTicket) says the same thing and reads better. Same with !isRaining instead of isRaining == false.
When you mix && and || in the same condition, use parentheses to make it clear what goes with what: (age >= 18 && hasTicket) || isGuest. C# has rules for the order without parentheses, but nobody reading your code should have to remember them.
Reading numbers without crashing
In the previous chapter you converted what the user types with int.Parse, and I warned you that if they type something that isn’t a number, the program crashes. Now that you know if, you can avoid that with int.TryParse:
Console.Write("How old are you? ");
if (int.TryParse(Console.ReadLine(), out int age))
{
Console.WriteLine($"Next year you'll be {age + 1}.");
}
else
{
Console.WriteLine("That's not a whole number.");
}
Console.Write is like Console.WriteLine, but it doesn’t move to the next line, so the user types right next to the question. If you type 30:
How old are you? 30
Next year you'll be 31.
And if you type thirty:
How old are you? thirty
That's not a whole number.
int.TryParse tries to convert the text. It returns a bool: true if it could and false if it couldn’t. That’s why it fits perfectly inside an if. The converted number comes out through out int age, which declares the age variable right there and fills it when the conversion works. Inside the if block you can use it like any other int.
From here on, every time you read a number from the user, use TryParse. In chapter 7 you’ll see exactly what happens when int.Parse fails and how to read that error.
switch: one value, many cases
When you compare the same variable against several fixed values, a long chain of else if gets hard to read. switch tidies it up:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 6:
case 7:
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Another day");
break;
}
Wednesday
switch (day) says which value you’re going to check. Each case is a possible value, followed by a colon and what to do. default is the case for everything else, like the final else.
Each case ends with break, which means “I’m done, leave the switch”. In C# it isn’t optional: if you remove it, the program doesn’t compile. The exception is an empty case, like 6, which sticks to the one below it. That way 6 and 7 share the same line.
The switch expression
C# has a second, shorter form for when what you want is to compute a value based on the case:
int day = 6;
string kind = day switch
{
6 or 7 => "a weekend day",
>= 1 and <= 5 => "a weekday",
_ => "not a valid day"
};
Console.WriteLine($"Day {day} is {kind}.");
Day 6 is a weekend day.
Read it like this: “depending on day, kind is this”. Each line has a pattern on the left of => and the result on the right. or and and inside patterns work like || and &&, and you can use comparisons like >= 1. The _ catches anything that didn’t match above. Just like with else if, the first pattern that matches wins.
My rule of thumb: if each case does something different (several lines, different messages), use if or the switch with case. If each case only produces a value, the switch expression is cleaner.
Mini-exercise: grade calculator
Write a program that:
- Asks the user for a score from 0 to 100.
- If what they type isn’t a whole number, tells them it isn’t a number.
- If it’s a number but outside the 0 to 100 range, tells them so.
- If the score is valid, tells them their letter grade: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, and below 60 is F.
Try it before looking at the solution. The pieces are TryParse, || and a chain of else if.
Suggested solution
Console.Write("Enter the score (0 to 100): ");
if (!int.TryParse(Console.ReadLine(), out int score))
{
Console.WriteLine("That's not a whole number.");
}
else if (score < 0 || score > 100)
{
Console.WriteLine("The score has to be between 0 and 100.");
}
else
{
string grade;
if (score >= 90)
{
grade = "A";
}
else if (score >= 80)
{
grade = "B";
}
else if (score >= 70)
{
grade = "C";
}
else if (score >= 60)
{
grade = "D";
}
else
{
grade = "F";
}
Console.WriteLine($"With {score} you got {grade}.");
}
Enter the score (0 to 100): 85
With 85 you got B.
Enter the score (0 to 100): 105
The score has to be between 0 and 100.
Notice the ! in front of int.TryParse: the first question is “did the conversion fail?”. That way both bad cases sit at the top and the good case sits at the end, without so much nesting. Also notice the grades go from highest to lowest, for the same reason as the temperature: the first true condition wins.
If you want to try the switch expression, you can replace the whole block that computes grade with this fragment:
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
Both versions do the same thing. Pick the one you find easier to read.
What you learned
- Comparison operators (
==,!=,<,>,<=,>=) produce abool. =assigns and==compares. If anifgives you error CS0029, look for that=.if,else ifandelsepick a path, and the first true condition wins.&&,||and!combine conditions. Each side of||is a complete comparison.int.TryParseinside anifreads numbers without crashing the program.switchwithcaseandbreakchecks one value against several cases; theswitchexpression computes a value based on the case.
In the next chapter your program learns to repeat: loops with while and for, and a guess-the-number game.
Stuck?
If something doesn’t compile or you don’t understand why the program took a certain path, send me a DM on Instagram or ask in the Discord community. Paste your code and the message you got, and we’ll look at it.
