BuildQuill
C# learning path
6 of 25
Lesson 6 of 25
Lesson 6Beginner17 min

C# Boolean Logic and Conditions

Turn rules into true-or-false expressions, choose among paths with if and switch, and avoid overlapping or unreadable conditions.

Before this lesson

  • Variables
  • Comparison operators
  • Parsed and validated input

Build Boolean expressions from comparisons

Order mutually exclusive branches correctly

Choose between if/else and switch

The short answer

A condition is an expression whose result is true or false. if runs a block when its condition is true; else if checks another possibility; else handles everything not matched earlier; switch maps one value or shape to clear alternatives.

01

A program needs a way to represent a rule

Until now, every statement ran in order. Useful programs must sometimes choose: accept or reject an input, apply one shipping rate, show a warning, or stop. The rule behind that choice becomes a Boolean expression—an expression whose only possible results are true and false.

Comparison operators create Boolean results. == asks whether values are equal, != asks whether they differ, and <, <=, >, and >= compare ordered values. A single = assigns; a double == compares. Reading the expression as a question helps: is orderTotal greater than or equal to 100?

C#
int availableSeats = 4;
int requestedSeats = 3;

bool enoughSeats = requestedSeats <= availableSeats;
Console.WriteLine(enoughSeats);

Expected output

True
02

Combine small facts with logical operators

The && operator means both sides must be true. The || operator means at least one side must be true. The ! operator reverses a Boolean. Prefer combining named facts when a rule would otherwise become a dense line of punctuation.

C# short-circuits && and || from left to right. If the left side of && is false, the whole expression is already false, so the right side does not run. That behavior lets a program check text.Length only after confirming text is not null, and it can avoid unnecessary work.

C#
int age = 21;
bool hasTicket = true;
bool isBanned = false;

bool canEnter = age >= 18 && hasTicket && !isBanned;
Console.WriteLine(canEnter);

Expected output

True

Good habits

  • Name complicated subconditions such as isWithinRange or hasPermission.
  • Use parentheses when grouping is not immediately obvious.
  • Do not write flag == true; if (flag) already asks whether it is true.
03

Only the first matching branch runs

In an if/else-if/else chain, C# tests from the top and runs the first matching block. Later branches are skipped even if their conditions would also be true. Order specific or higher-priority rules before broad rules.

A grade of 95 is also at least 80. Testing >= 80 first would label it B and never reach >= 90. This is not a compiler error; it is a logic error, which means the program runs but applies the wrong rule.

C#
using System;

class Program
{
  static void Main()
  {
      int score = 86;

      if (score >= 90)
          Console.WriteLine("A");
      else if (score >= 80)
          Console.WriteLine("B");
      else if (score >= 70)
          Console.WriteLine("C");
      else
          Console.WriteLine("Needs review");
  }
}

Expected output

B
04

Use switch when one subject has named cases

switch is useful when one value is compared with a set of discrete cases, such as a menu command, status, or day category. It keeps the subject visible and makes the fallback explicit with default. if is usually clearer for ranges, unrelated conditions, or rules that combine several variables.

Every case in a traditional switch must end its path, commonly with break or return. Modern switch expressions can return a value more compactly, but the statement form below makes execution flow visible and works in the course compiler.

SituationPreferWhy
Ranges such as age or priceif / else ifConditions express boundaries naturally
Several facts combinedifEach branch can use a different expression
One value matched to named casesswitchCases remain easy to scan
Two-value assignmentConditional operator ?: cautiouslyConcise when both choices are simple
C#
using System;

class Program
{
  static void Main()
  {
      string command = "save";

      switch (command)
      {
          case "open":
              Console.WriteLine("Opening file");
              break;
          case "save":
              Console.WriteLine("Saving file");
              break;
          case "quit":
              Console.WriteLine("Closing program");
              break;
          default:
              Console.WriteLine("Unknown command");
              break;
      }
  }
}

Expected output

Saving file

Quick knowledge check

Answer before you reveal.

01If the first and third conditions are true, which branch runs?

Only the first matching branch in the chain runs.

02When the left side of false && SomeMethod() is false, does SomeMethod run?

No. && short-circuits because the overall result cannot become true.

Practice challenge

Now build it without copying.

Write a cinema ticket rule. A child under 12 pays 6, a senior aged 65 or above pays 7, a member pays 9, and everyone else pays 12. Reject ages outside 0–120.

You are done when

  • Invalid age is handled before ticket pricing
  • Exactly one price branch runs
  • Boundary ages 11, 12, 64, and 65 produce the intended prices

Stretch: Add a weekend surcharge without duplicating the whole pricing chain.

Open challenge in playground

Lesson checkpoint

One small step locks it in

Mark this lesson complete, then keep the momentum going.

Complete and continue

Clear up the details

Frequently asked questions

Should I always use braces around one-line branches?

Braces are strongly recommended. They reduce mistakes when another statement is added and make branch boundaries visible.

What is the ?: operator?

The conditional operator chooses between two expressions: condition ? valueWhenTrue : valueWhenFalse. Use it for a small value choice, not to compress multi-step logic.

Can switch handle more than exact values?

Modern C# supports patterns and when guards. Learn the basic one-subject model first; pattern matching is most useful when it makes type or shape rules clearer.