contains conditional in csharp

In C#, you can use if-else, switch-case, and ternary conditional operators for creating conditional statements.

if-else statement

The if-else statement is used to execute a block of code if the condition is true, and another block of code if the condition is false. Here is an example:

main.cs
int num = 10;
if (num > 0)
{
    Console.WriteLine("Number is positive.");
}
else
{
    Console.WriteLine("Number is negative.");
}
132 chars
10 lines

In this example, we compare the value of the num variable with 0. If num is greater than 0, then the message "Number is positive." will be displayed. Otherwise, the message "Number is negative." will be displayed.

switch-case statement

The switch-case statement is used to select one of many code blocks to execute based on the value of an expression. Here is an example:

main.cs
int day = 4;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    case 5:
        Console.WriteLine("Friday");
        break;
    default:
        Console.WriteLine("Invalid day.");
        break;
}
427 chars
23 lines

In this example, the value of day is compared with each case. If the value of day matches one of the case values, then the corresponding message will be displayed. If the value of day does not match any of the case values, then the default message will be displayed.

Ternary conditional operator

The ternary conditional operator is used to assign a value based on a condition. Here is an example:

main.cs
int num = 10;
string result = (num > 0) ? "Number is positive." : "Number is negative.";
Console.WriteLine(result);
116 chars
4 lines

In this example, we check if num is greater than 0. If num is greater than 0, then the value of result will be "Number is positive." Otherwise, the value of result will be "Number is negative."

related categories

gistlibby LogSnag