Skip to content

C# - If

The if statement is a fundamental control flow construct in programming. It allows your code to make decisions and execute a specific block of code only when a given condition is true.

The syntax of an if statement is straightforward:

if (boolean_expression)
{
// This block of code executes if the boolean_expression is true.
}

The boolean_expression must evaluate to either true or false. If it’s true, the code inside the curly braces {} is executed. If it’s false, the code block is skipped, and execution continues with the next statement after the if block.

You can visualize the flow of an if statement like this:

( Start )
|
v
+---------------------+
| Is condition true? | -- No --> ( Skip block and continue )
+---------------------+
|
Yes
|
v
+---------------------+
| Execute code in |
| the 'if' block |
+---------------------+
|
v
( Continue after block )

Here’s a simple example that checks a student’s score to see if they passed.

// Modern C# with top-level statements
int score = 85;
int passingScore = 60;
Console.WriteLine($"Your score is: {score}");
if (score >= passingScore)
{
Console.WriteLine("Congratulations, you passed!");
}
// This line executes regardless of the condition
Console.WriteLine("Finished checking score.");

When the above code is compiled and executed, it produces:

Your score is: 85
Congratulations, you passed!
Finished checking score.

A common use for if statements is to process items in a collection and take action only on the ones that meet specific criteria. In this example, we filter a list of products to show only those that are on sale.

using System;
using System.Collections.Generic;
// A simple record to represent a product
public record Product(string Name, decimal Price, bool IsOnSale);
var products = new List<Product>
{
new Product("Laptop", 1200m, false),
new Product("Mouse", 25m, true),
new Product("Keyboard", 75m, true),
new Product("Monitor", 300m, false)
};
Console.WriteLine("--- Products On Sale ---");
foreach (var product in products)
{
// Use an if statement to check the IsOnSale property
if (product.IsOnSale)
{
Console.WriteLine($"- {product.Name} is available for just ${product.Price}!");
}
}

The output will only include the products where IsOnSale is true:

--- Products On Sale ---
- Mouse is available for just $25!
- Keyboard is available for just $75!

1. Always Use Braces {}: Even if your if block contains only one line, it’s a widely-accepted best practice to always use curly braces. This improves readability and prevents bugs if you later add more lines to the block.

// Good practice: clear and safe
if (condition)
{
DoSomething();
}
// Bad practice: can lead to bugs
if (condition)
DoSomething();
DoSomethingElse(); // This line is NOT part of the if statement!

2. Combine with else and else if: The if statement is often paired with else (to execute code when the condition is false) and else if (to check multiple conditions in sequence). These allow you to build more complex decision-making logic.

3. Keep Conditions Simple: If your boolean expression becomes very long and complex, consider refactoring it into a separate boolean variable or a method. This makes your if statement easier to read.

bool canUserAccessFile = user.IsAuthenticated && (user.HasReadPermission || user.IsAdmin); if (canUserAccessFile) { ... }