In C#, conditional statements are used to execute a certain block of code only if a specified condition is true. There are three types of conditional statements in C#: if
, else
, and switch
.
The if
Statement
The if
statement is used to execute a block of code only if a certain condition is true. Here's an example:
csharpint x = 10;
int y = 5;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
In the code above, we declared two variables x
and y
, and used the if
statement to check if x
is greater than y
. If the condition is true, the code inside the curly braces {}
will be executed and the message "x is greater than y" will be displayed.
The else
Statement
The else
statement is used to execute a block of code if the condition specified in the if
statement is false. Here's an example:
csharpint x = 10;
int y = 5;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
else
{
Console.WriteLine("x is not greater than y");
}
In the code above, we used the else
statement to specify what should happen if the condition in the if
statement is false. If the condition is false, the code inside the curly braces of the else
statement will be executed and the message "x is not greater than y" will be displayed.
The switch
Statement
The switch
statement is used to execute a block of code based on the value of a specified expression. Here's an example:
csharpint day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
In the code above, we declared a variable day
and used the switch
statement to check its value. Based on the value of day
, a different message will be displayed. If the value of day
is not equal to 1, 2, or 3, the code inside the default
case will be executed and the message "Invalid day" will be displayed.
In conclusion, conditional statements in C# allow you to execute a block of code only if a specified condition is true. By using the if
, else
, and switch
statements, you can write more flexible and powerful programs.