C# if Statement


The if statement in C# is used to execute a block of code based on a condition. It allows for decision-making in programs, enabling the program to perform different actions depending on whether a condition evaluates to true or false.

1. Syntax of the if Statement

The basic structure of an if statement in C# is as follows:

if (condition) { // Code to execute if the condition is true }
  • condition: This is a boolean expression that evaluates to either true or false.
  • If the condition is true, the block of code inside the curly braces {} is executed.
  • If the condition is false, the code inside the block is skipped.

2. Example of a Basic if Statement

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

Explanation:

  • In this example, the condition number > 5 is evaluated.
  • Since 10 is greater than 5, the condition is true, so the message "The number is greater than 5." is printed to the console.