If Statements
The if statement is a fundamental control flow structure in C# used to execute a block of code when a specified condition is true. The syntax of an if statement is:
if (condition) {
// Code block to execute if the condition is true
}
For example, the following code checks if a variable age is greater than or equal to 18:
int age = 25;
if (age >= 18) {
Console.WriteLine("You are an adult.");
}
If-Else Statements
The if-else statement extends the if statement by adding an alternative block of code to execute when the condition is false. The syntax of an if-else statement is:
if (condition) {
// Code block to execute if the condition is true
} else {
// Code block to execute if the condition is false
}
For instance, the following code checks if a variable score is greater than or equal to 90:
int score = 85;
if (score >= 90) {
Console.WriteLine("Excellent!");
} else {
Console.WriteLine("Try harder next time.");
}
Short-Hand If-Else Statements (Ternary Operator)
The ternary operator, also known as the conditional operator, provides a concise way to express an if-else statement in a single line. It has the following syntax:
condition ? trueExpression : falseExpression;
The expression evaluates the condition, and if it is true, the trueExpression is evaluated and returned; otherwise, the falseExpression is evaluated and returned.
For example, the following code assigns the value "Pass" to the result variable if the score is greater than or equal to 60, and "Fail" otherwise:
int score = 75;
string result = (score >= 60) ? "Pass" : "Fail";
Console.WriteLine(result); // Output: Pass
Conclusion
The if, if-else, and ternary operator are essential tools for controlling the flow of execution in C# programs. They allow programmers to make decisions based on conditions and execute different code blocks accordingly. These control flow structures are widely used in various programming tasks, from simple condition checking to complex decision-making logic.