C# Basics - Conditional Statements
Posted on June 24, 2024 (Last modified on October 11, 2024) • 2 min read • 349 wordsVideo is in Swedish
Conditional statements in C# are used to control the flow of execution based on certain conditions or criteria. They allow you to make decisions and execute different blocks of code depending on whether a condition is true or false.
There are several types of conditional statements in C#, including if, else, switch, and case. The most common one is the if statement, which checks if a condition is true or false and executes a block of code accordingly.
Here’s an example of how to use an if statement in C#:
int age = 25;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
In this example, the program checks if the variable age
is greater than or equal to 18. If it is, then it will print “You are eligible to vote.” on the console.
The else statement can be used in conjunction with an if statement to execute a different block of code when the condition is false:
int age = 25;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not yet eligible to vote.");
}
In this example, if age
is less than 18, then it will print “You are not yet eligible to vote.” on the console.
The switch statement allows you to execute different blocks of code based on the value of a variable. It’s useful when you have multiple cases that need to be handled for a single variable:
int day = 5;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
// more cases...
}
In this example, the program checks the value of day
and prints “Monday” if it’s 1, “Tuesday” if it’s 2, and so on.
Conditional statements are a powerful tool in C# that allow you to control the flow of your code based on certain conditions. They can be used to make decisions, execute different blocks of code depending on whether a condition is true or false, and more. Understanding how to use them effectively will help you write better and more efficient code.
Swedish