c
  1. c-else

C# else Statement

Syntax

if (condition)
{
  // code to execute if condition is true
}
else
{
  // code to execute if condition is false
}

Example

int x = 10;

if (x > 15)
{
  Console.WriteLine("x is greater than 15");
}
else
{
  Console.WriteLine("x is less than or equal to 15");
}

Output

x is less than or equal to 15

Explanation

The else statement in C# is used in conjunction with the if statement to execute a block of code if the condition specified in the if statement is false. The else statement is optional, but it provides an alternative code block to execute when the if condition is not met.

Use

The else statement is used to provide an alternative code block to execute whenever the condition specified in the if statement is false. This can be useful when you need to execute different code based on the outcome of a conditional statement.

Important Points

  • The else statement is always used in conjunction with the if statement.
  • The else statement is optional and is only executed if the condition in the if statement is false.
  • An else if statement can be used to provide additional conditions to check if the condition in the if statement is false.

Summary

The else statement in C# provides an alternative block of code to execute when the condition specified in the if statement is false. It is optional but is often used to check for multiple conditions or provide fallback logic when a specific condition is not met. Knowing how to use else statements effectively can improve the functionality and efficiency of your C# code.

Published on: