c-sharp
  1. c-sharp-if-else

C# if-else

Syntax

if (condition)
{
    // Code to be executed if condition is true
}
else
{
    // Code to be executed if condition is false
}

OR 

if (condition1)
{
    // Code to be executed if condition1 is true
}
else if (condition2)
{
    // Code to be executed if condition2 is true
}
else
{
    // Code to be executed if all conditions are false
}

Example

int num = 10;

if (num > 0)
{
    Console.WriteLine("The number is positive.");
}
else if (num == 0)
{
    Console.WriteLine("The number is zero.");
}
else
{
    Console.WriteLine("The number is negative.");
}

Output

The number is positive.

Explanation

In C#, the if-else statement is used for conditional execution of code. The syntax consists of the keyword "if", followed by the condition to be evaluated. If the condition is true, the code block inside the if statement is executed. If the condition is false, the code block inside the else statement is executed.

In the second example, we have used the else if statement to provide multiple conditions to evaluate. If the first condition is false, it checks the second condition, and so on. If none of the conditions are true, the code block inside the else statement is executed.

Use

The if-else statement is commonly used in C# to implement decision-making logic in programs. It allows the program to execute different sections of code based on the value of certain conditions. It is a powerful tool for controlling the flow of execution of a program.

Important Points

  • The if-else statement is used for conditional execution of code.
  • The condition evaluated must return a boolean value (true or false).
  • Multiple conditions can be evaluated using the else if statement.
  • The else statement is optional.
  • The code block within an if statement or else if statement must be enclosed in braces {}.

Summary

The if-else statement is a fundamental part of C# programming that allows for conditional execution of code. It is used extensively in most programs to implement decision-making logic based on the evaluation of conditions. By using if-else statements, a programmer can easily control the flow of execution of a program and produce more robust and reliable software.

Published on: