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 eithertrue
orfalse
.- If the
condition
istrue
, the block of code inside the curly braces{}
is executed. - If the
condition
isfalse
, 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 than5
, the condition istrue
, so the message"The number is greater than 5."
is printed to the console.