An if statement in C# allows you to execute a block of code based on a condition. If the condition evaluates to true, the code block runs; otherwise, it’s skipped. Let’s explore the key aspects:
Basic Syntax
The basic structure of an if statement looks like this:
if (condition)
{
// Code to execute if the condition is true
}
Example
int i = 10, j = 20; if (i < j) { Console.WriteLine("i is less than j"); }
In this case, since i is indeed less than j, the message “i is less than j” will be displayed.
Adding More Conditions
else if and else:-else if Statement: When you have multiple conditions, use else if after the initial if. It’s evaluated only if the preceding condition(s) are false.
if (i == j) { Console.WriteLine("i is equal to j"); } else if (i > j) { Console.WriteLine("i is greater than j"); } else if (i < j) { Console.WriteLine("i is less than j"); }
Here, the output will be “i is less than j.”
else Statement: The else block executes when none of the preceding conditions are true.
Comparison Operators
Use comparison operators like ==, !=, >=, and < to create meaningful conditions. For example:
if (i != j) { Console.WriteLine("i is not equal to j"); }
Function Calls as Conditions
You can use functions within if statements if they return a boolean value.
static bool IsGreater(int i, int j) { return i > j; }
// Usage if (IsGreater(i, j)) { Console.WriteLine("i is less than j"); }
Nesting and Logical Operators
Nesting: You can nest if statements inside each other for more complex logic. Logical Operators: Combine conditions using && (AND) or || (OR).
Practical Use Cases
Automated Tasks: Send emails, process orders, or move files based on specific events. Data Processing: Collect, transform, and transfer data across systems. System Integration: Connect on-premises and cloud systems. Monitoring: Set up alerts and notifications.