C# if Statement

The if statement in C# is a control flow statement that allows you to execute a block of code only if a specified condition evaluates to true. It is fundamental for decision-making in programming.

Key Topics

1. Syntax of if Statement

if (condition)
{
    // Code to execute if condition is true
}

The condition inside the parentheses is evaluated. If it is true, the code block inside the braces is executed.

2. Basic if Statement Example

Example: Checking a Number

int number = 10;
if (number > 5)
{
    Console.WriteLine("The number is greater than 5.");
}

Output:

The number is greater than 5.

Code Explanation: The condition number > 5 evaluates to true because 10 is greater than 5. Therefore, the message is printed to the console.

3. Conditional Expressions

Conditional expressions can use comparison operators (==, !=, >, <, etc.) and logical operators (&&, ||, !).

Example: Using Logical Operators

bool isMember = true;
int age = 20;
if (isMember && age >= 18)
{
    Console.WriteLine("Access granted.");
}

Output:

Access granted.

Code Explanation: Both conditions isMember and age >= 18 are true, so the message is printed.

4. Best Practices for if Statements

  • Keep conditions simple and readable.
  • Use braces { } even for single-line statements to improve readability and prevent errors.
  • Avoid deep nesting by refactoring code or using functions.

Key Takeaways

  • The if statement executes code based on a condition.
  • Conditions use comparison and logical operators.
  • Proper syntax and best practices enhance code readability and maintainability.