C# If, Else If, and Else: Choose the Right Path
A condition answers true or false; a branch decides which statements run. Learn to choose exclusive paths, order thresholds, keep independent checks separate, and stop invalid paths before using their values.
What you will understand
- Trace which statements run for true and false conditions.
- Use if/else for alternative outcomes and else-if for first-match categories.
- Distinguish an exclusive chain from independent if statements.
- Use braces and recognize accidental empty statements.
- Apply early guards without continuing a rejected path.
- Assign local results on every path that reaches their use.
- Use a short conditional expression when selecting a simple value.
- Verify a delivery quote at every threshold and option.
An if statement chooses whether a block runs
A Boolean expression describes a condition; an if statement uses that answer to select statements. Read it as if this condition is true, run this block. The statements outside the block continue normally unless the selected path returns, throws or otherwise transfers control.
Write the condition inside parentheses and the body inside braces. The braces define which statements belong together. A false condition skips that body; it does not stop the whole program. The before-and-after example makes the continuing path visible.
You need the Boolean and operator lessons before this one. Predict the path before running each complete Program.cs, then change the fixed source values. One program intentionally fails compilation so you can inspect a missing assignment path. Other deliberately broken programs compile but choose incorrect behavior.
Program.cs · Run a block only when its condition is true
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Before check
Draft saved.
After check
The condition inside parentheses is bool. When it is true, the braced block runs; when false, that block is skipped. The final message is outside the block and runs either way. The example prints a supplied draft state; it does not save a file.
Use else when the two outcomes are alternatives
An if/else decision has a true branch and a false branch. For the ordinary Boolean condition shown here, exactly one of those blocks runs. The else does not have another condition; it covers everything that made its associated if false.
Choose messages that match the actual condition. An else for seatsAvailable > 0 includes zero and negative values. If negative stock is invalid data, validate that separately rather than pretending the branch proved an ordinary sold-out state.
After the selected block finishes, execution continues after the whole decision. You do not need a break statement to stop an if branch. break is used for other constructs later in the course, while return ends the current method or this top-level run.
Program.cs · Choose exactly one of two branches
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
No seats available.
Check complete.
The if and else form one decision. Exactly one branch runs for this ordinary Boolean condition. else has no condition of its own: it handles the false case of the preceding if. The later message runs after the chosen branch finishes.
An else-if chain selects the first matching category
Use else if to test another condition only after previous conditions in the chain were false. Once a condition is true, that branch runs and the rest of the chain is skipped. The final else is the fallback when none of the earlier conditions matched.
Order overlapping thresholds deliberately. For a highest-earned category, a broad low threshold can capture a value before it reaches the stricter high threshold. Put the appropriate specific condition first, or rewrite the intervals so the intended order is obvious.
You do not always need to repeat upper bounds in every branch. In the delivery example, reaching subtotal >= 50 means the earlier >= 100 test already failed. That context defines the middle interval. Test exact thresholds and values immediately on either side to verify the categories.
Program.cs · Pick the first matching delivery band
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery: 3.00
Checks proceed from top to bottom. At 75, the first condition is false and the second is true, so the middle branch runs. Its implicit upper bound comes from reaching it only after subtotal >= 100 was false. The final else covers values below 50 under this exercise’s nonnegative-subtotal assumption.
Program.cs · A broad first condition can hide a later category
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Core complete.
Every value satisfying >= 5 also satisfies >= 3, so the later branch is never selected. The compiler does not generally reject this overlapping runtime condition. If one highest category is intended, check the stricter threshold first. If both messages are intended, use independent checks.
Separate independent questions from exclusive categories
Two standalone if statements are two decisions. Both may run, neither may run, or only one may run. That is useful for independent messages or optional adjustments, but it can be wrong when one choice must exclude another.
An if/else-if chain represents one selection. Do not replace every independent check with else if merely to make the code shorter. Ask whether multiple outcomes are allowed. A learner can finish both core work and extra practice, while a quote should choose one base-delivery band.
Assignments make this distinction especially important. A later independent if can overwrite a value selected by an earlier one. Trace each assignment in order, not just the first condition that looks relevant. The guided repair below demonstrates the overwritten-fee bug.
Program.cs · Independent if statements can both run
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Core steps complete.
Extra practice complete.
These are separate questions, so both conditions are evaluated and both messages can print. An else-if chain would instead choose only one category. Use independent if statements when multiple outcomes are allowed, and a chain when the outcomes must be exclusive.
Braces define the branch; indentation and semicolons can mislead
Without braces, an if controls only its single following embedded statement. A second indented statement is not automatically part of the branch. Use braces consistently so the intended body remains clear when a program grows.
A semicolon directly after if (condition) forms an empty body. A following braced block then stands on its own and runs regardless of that condition. The compiler can warn about the empty statement, but a warning is not the same as a compilation failure.
Nested decisions need equally clear ownership. An else associates with the nearest eligible if according to syntax; braces remove ambiguity for readers. Keep nesting shallow when possible and use early rejection guards when they express the flow more directly.
Program.cs · Indentation does not create a block
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
This line is outside the if.
Without braces, only the next statement belongs to this if. Indentation is for people; it does not change the syntax. Use braces consistently when teaching and maintaining branches so a second statement is not accidentally unconditional.
Program.cs · An accidental semicolon creates an empty statement
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
This block runs anyway.
The semicolon immediately after the condition is the if body: an empty statement. The following braced block is separate and runs unconditionally. The compiler can warn, but this code can still compile. Remove the semicolon and attach the intended block to the if.
Program.cs · Make each nested decision answer a smaller question
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Activate the account first.
The inner if is considered only when lessonOpen is true. Braces show which else belongs to which if. Nesting can clarify a short dependent decision, but several rejection guards often make a longer flow easier to read. These fixed flags do not implement account authorization.
Reject invalid input before entering the successful path
A rejection message does not stop execution by itself. If later statements must not run after rejection, explicitly end that path. In these top-level examples, return ends the run before a subtotal or quote is printed.
A guard handles an invalid state early, then lets the remaining code focus on a valid case. Several guards can explain different failures in a deliberate priority order. The first one that returns determines the message; a program reporting all errors would require a different flow.
Keep the scope of a guard honest. A positive quantity check does not prove available stock, and a negative-subtotal guard does not define a complete checkout policy. These programs show local control flow and quoted amounts without creating orders or charging anyone.
Program.cs · Reject an invalid quantity before calculating
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Quantity must be positive.
return ends this top-level run, so the subtotal statement is not reached. Merely printing an error would not stop later code. The guard keeps the remaining path focused on valid positive quantities; additional rules such as an upper limit would be separate checks.
Assign values on every path that reaches their use
A local variable must be definitely assigned before it is read. If one branch assigns a message and another path continues without assigning it, the compiler rejects the read. This rule is about execution paths, not whether one sample input happens to take the assigned path.
An if/else can assign a result on both paths. A complete chain can also choose one result. Alternatives include a meaningful initial value or an early return on a path that cannot produce a valid result. Avoid invented defaults that hide an unhandled case.
For a brief choice between two values, the conditional operator condition ? first : second can be readable. It is an expression that returns a selected value, rather than a block of statements. Do not compress a multi-stage decision into nested conditional expressions if that makes its behavior harder to explain.
Program.cs · Assign a result on every continuing path
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery: 0.00
The local delivery has no initial value, but both branches assign it. Every path reaching the output has an assigned decimal, so this is valid. This two-band example has its own stated rule; it is not the three-band policy used in the later repair.
Program.cs · A missing assignment path fails compilation
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Compilation fails: message may be unassigned.The false path reaches the output without assigning message. The compiler’s definite-assignment rule protects this local read. Add a meaningful else assignment, initialize a deliberate default, or exit the false path; do not invent a misleading value just to suppress the diagnostic.
Program.cs · Choose a short value with the conditional operator
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Available
Read condition ? valueWhenTrue : valueWhenFalse as a compact expression returning one value. Only the selected expression is evaluated. Use it for a short label when it stays clear; use if/else for several statements, rejection feedback or a multi-stage decision.
Trace a decision from its inputs to its selected path
For each example, write down the source value, evaluate the first condition and record whether its block runs. In a chain, move to the next condition only if the previous one was false. With independent checks, continue to the next if regardless of whether the earlier one ran.
Test every branch and boundary. For thresholds of fifty and one hundred, include values below fifty, exactly fifty, just below one hundred and exactly one hundred. A single subtotal of seventy-five cannot prove that the highest or lowest band is correct.
Finally, separate classification from optional adjustments. The lab chooses one base fee and then independently decides whether to add an express surcharge. Its test cases include invalid input, exact thresholds and both express states so that an accidental overwrite or bypass is visible.
Guided repair: stop delivery bands overwriting each other
A subtotal of 120 should receive a base delivery fee of zero, but the program prints 3.00. Trace both assignments and repair the policy as a single exclusive choice, with a guard for negative subtotals.
Program.cs · Delivery bands overwrite each other
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery: 3.00
Both independent conditions are true, so the second assignment overwrites the free-delivery amount. The intended rule chooses one delivery band. A default of six does not prevent later assignments from replacing earlier decisions.
Repair checkpoints
- Explain why two independent checks overwrite the zero fee.
- Reject subtotal < 0 with a message and return.
- Choose 0 for subtotal >= 100, 3 for subtotal >= 50 and below 100, otherwise 6.
- Test 49.99 → 6.00, 50 → 3.00, 99.99 → 3.00 and 100 → 0.00.
- Every accepted path must assign the fee before output; negative input must not print a fee.
Reveal the repair and explanation
Program.cs · Choose one delivery band after rejecting invalid input
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery: 0.00
The guard rejects a negative subtotal first. The chain then assigns exactly one fee, testing the highest threshold first. Every continuing path assigns delivery before it is read. The policy is illustrative and fixed: this program does not charge a buyer.
Independent lab: a dispatch quote
Build a dispatch quote using one base-delivery band and an independent express option. First reject a negative subtotal, then classify the subtotal, then add an eight-unit express surcharge only when selected.
Acceptance checklist
- Keep subtotal = 120m and express = true for the reference run.
- Reject negative subtotal with the exact feedback in the solution and end the run.
- Choose one base fee: 6 below 50, 3 from 50 up to but excluding 100, 0 at 100 or above.
- Apply an 8m express surcharge after choosing the base fee.
- Print Base fee: 0.00 and Delivery quote: 8.00 for the reference inputs.
- Use a chain for the base bands and a separate if for the option; this exercise only prints a quote.
Program.cs · Dispatch quote starter
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Delivery quote: 11.00
The express addition is independent by design, but the base-fee bands should be exclusive. The starter overcharges this reference quote because two base-band assignments run. It also has no negative-subtotal rejection. Repair the base classification before applying the express option.
Show hints
- Put the highest threshold first so it is not hidden by the lower threshold.
- Assign baseFee on every valid continuing path.
- Copy baseFee into delivery before adding the optional surcharge.
Reveal the reference solution
Program.cs · Dispatch quote reference solution
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Base fee: 0.00
Delivery quote: 8.00
The chain chooses one base band. A separate if adds the optional express surcharge once, even when the base fee is zero. That separation matches two different questions: which base fee applies, and whether the express option is selected. The printed quote has no payment or delivery side effect.
Changed-input checks
- Subtotal 0 with standard delivery: base 6.00 and quote 6.00.
- 49.99, 50, 99.99 and 100 must select bases 6, 3, 3 and 0 respectively.
- For each accepted subtotal, express adds exactly 8 and standard adds zero.
- A negative subtotal reports an error and prints neither a base fee nor a quote.
- The exact threshold 100 still pays the express surcharge when selected.
Recap: choose the right branching structure
Choose exclusive branches for one category, independent checks for multiple actions, and guards for rejected paths. Confirm that every continuing path assigns the values it later uses.
if (condition) { ... }- Run its body only when the Boolean condition is true.
if / else- Choose one of two alternative branches.
else if- Test another category only after earlier conditions were false.
independent if statements- Allow multiple actions when the questions are independent.
{ ... }- Define the statements belonging to a branch; indentation is not grouping.
return- End this top-level run or the current method, not merely the branch.
definite assignment- Assign a local on every path that reaches its read.
condition ? first : second- Return one of two short expression results.
Frequently asked questions
Do I need break after an if block?
No. Execution naturally continues after the selected branch. An else-if chain already skips its remaining alternatives after a match. break belongs to other constructs such as loops and switch.
Can two separate if statements both run?
Yes. Each is an independent decision. Use a chain only when the outcomes should be exclusive.
Why does the first matching branch matter?
Later conditions in the same chain are not tested after a true condition selects a branch. A broad early condition can therefore hide a more specific later category.
Why use braces for a single statement?
They make branch ownership explicit and prevent a newly added statement from accidentally running outside the intended condition.
Does printing an error stop the program?
No. Use the appropriate control transfer, such as return in these top-level examples, when the rejected path must not continue.
Why does a variable assigned inside one if still fail compilation?
Another path may reach the read without assigning it. Assign every continuing path, choose a meaningful initial value or exit the path that cannot produce a result.
Can you trace the selected path?
Trace first-match selection, independent conditions, braces and continuing paths. Read each explanation after checking your answers.
Next step and references
Branching turns conditions into selected statements. Choose whether outcomes are exclusive or independent, order thresholds deliberately, and end rejected paths before using their values. Test every branch and the exact boundaries between them.
Next is C# Switch Statements and Expressions. You will choose behavior from discrete values, handle an unknown choice and compare a statement with an expression that returns a result.
Official references
Original SovranCode explanations, examples and exercises. Technical details were checked against these references.
Last updated: .