Conditional Statements in c#?| What are the alternative ways of writing if-else conditions? When to use what?

In C#, conditional statements are used to make decisions based on certain conditions. These statements allow your program to execute different code blocks depending on the evaluation of one or more conditions. The main conditional statements in C# are if, else, else if, switch, and the conditional operator (? :).

If statement:

  • The if statement allows you to execute a block of code if a specified condition is true.

Example:

int number = 10;
if (number > 0)
{
    Console.WriteLine("Number is positive.");
} 

If-else statement:

  • The if-else statement allows you to execute one block of code if a condition is true and another block of code if the condition is false.
Example:
int number = -5;
if (number > 0)
{
    Console.WriteLine("Number is positive.");
}
else
{
    Console.WriteLine("Number is not positive.");
}

Else-if statement:

  • The else if statement allows you to check multiple conditions in sequence and execute different code blocks based on the first condition that evaluates to true.
Example:
int number = 0;
if (number > 0)
{
    Console.WriteLine("Number is positive.");
}
else if (number < 0)
{
    Console.WriteLine("Number is negative.");
}
else
{
    Console.WriteLine("Number is zero.");
}

Switch statement:

  • The switch statement allows you to choose one of many code blocks to execute based on the value of a variable or an expression.

Example:

int dayOfWeek = 3;
switch (dayOfWeek)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Invalid day");
        break;
}

Conditional operator (? :):

  • The conditional operator, also known as the ternary operator, provides a concise way to write simple conditional expressions.
  • It evaluates a condition and returns one of two expressions depending on the result of the condition.

Example:

int number = 10;
string result = (number > 0) ? "Number is positive." : "Number is not positive.";
Console.WriteLine(result);

Conditional statements allow your program to perform different actions based on specific conditions, making your code more flexible and responsive to different scenarios. They are fundamental building blocks for controlling the flow of execution in your C# programs.


 

 

Post a Comment

Previous Post Next Post