Conditional Statements in C#: If, Else, and Switch - Your Guide to Controlling Program Flow

Thungex
Conditional Statements in C#: If, Else, and Switch - Your Guide to Controlling Program Flow
C# Coding Example

Think of this you’re planning a day. You’ve got a list of things you’d love to do, but there’s one catch: you only have so much time. Maybe if you finish work early, you’ll head out for a coffee. If it’s already evening, you might just settle in with a good movie. Or, if there’s a big chunk of time, maybe it’s perfect for that long-awaited bike ride. Each choice depends on your time, your mood, and maybe even the weather.

Programming isn’t so different. When writing code, we often need to make similar choices—whether to show a message to a user, hide a menu, or offer a discount. In C#, these choices happen with conditional statements. Let’s look at how if, else, and switch statements help us steer the flow of a program based on what’s happening at the moment.

Starting Simple with if: Making Basic Choices

The if statement is where it all starts. Think of it as a straightforward “if this, then that” decision. Imagine you’re building a site where users can either be logged in or not. With an if statement, you can welcome them back if they’re logged in or do nothing if they aren’t.

Example:

bool isLoggedIn = true;

if (isLoggedIn) {
    Console.WriteLine("Welcome back! Good to see you.");
}

In this example:

  • if checks if the condition inside the parentheses (isLoggedIn) is true.
  • If isLoggedIn is true, the message inside { } runs.

That’s all there is to it! This example might be simple, but if statements like these help make code respond only when certain conditions are met.

Adding an else Option: Handling “What If Not?”

Now, what if the user isn’t logged in? With an else statement, you can give the program an alternate action. Just like having a backup plan—if your favorite coffee shop is closed, you go to the next one. In code, else handles the scenario when the if condition doesn’t pass.

Example:

bool isLoggedIn = false;

if (isLoggedIn) {
    Console.WriteLine("Welcome back!");
} else {
    Console.WriteLine("Hello! Please log in to continue.");
}

Here’s what’s happening:

  • If isLoggedIn is true, the “Welcome back!” message displays.
  • But if isLoggedIn is false, the else message displays instead, prompting the user to log in.

The else is your “plan B.” It runs only when the if condition isn’t met. This way, your code can cover multiple possibilities.

Adding More Layers with else if: Handling More than Two Choices

Sometimes, it’s not just yes-or-no. Maybe you’re building a rewards program where members earn different perks based on their points. If they have 500 or more points, they get a big reward. If they have over 100, they get a smaller one. And for everyone else, they’re encouraged to keep earning.

Example:

int points = 250;

if (points >= 500) {
    Console.WriteLine("Congratulations! You've earned a premium reward.");
} else if (points >= 100) {
    Console.WriteLine("Nice work! You've earned a standard reward.");
} else {
    Console.WriteLine("Keep going! More rewards await.");
}

In this setup:

  • The code first checks if points are 500 or higher. If so, it stops there and shows the premium reward message.
  • If points aren’t high enough for that, the program moves to the next condition checking if the user has at least 100 points.
  • If neither condition is met, it defaults to the last message.

With else if, you can layer conditions checking one after another. Only one of these blocks will run—the first condition that matches gets the spotlight.

The switch Statement: A Clearer Way to Handle Fixed Choices

If you’re dealing with multiple specific options like a list of roles in a user profile a switch statement can help keep your code clean and organized. Think of switch as a way to make clear specific choices without a mess of else ifs.

Example:

string userRole = "Editor";

switch (userRole) {
    case "Admin":
        Console.WriteLine("Welcome, Admin! You have full access.");
        break;
        
    case "Editor":
        Console.WriteLine("Welcome, Editor! You can edit and review content.");
        break;
        
    case "Viewer":
        Console.WriteLine("Welcome, Viewer! You can browse content.");
        break;
        
    default:
        Console.WriteLine("Role not recognized. Contact support.");
        break;
}

What’s happening here:

  • switch checks the value of userRole.
  • Each case matches a specific role and gives a unique response.
  • break tells the program to stop after finding a match preventing it from checking further.
  • default is a catch-all option running if no cases match.

The switch statement is ideal when you have multiple fixed values to compare. It’s easy to read and keeps code from getting cluttered.

Real-World Situations Where Conditionals Shine

Conditionals come in handy almost everywhere in programming. Here are some real examples where they’re useful:

  • User Authentication: Before showing personalized content check if a user is logged in.
  • Dynamic Content Display: Use conditionals to adjust content based on a user’s profile settings.
  • Game Mechanics: Determine player rewards or levels based on their score or progress.

Writing Clean Conditional Code

A few small tips can help keep your conditionals clean and readable:

  • Avoid “if” Overload: If you have too many nested if statements consider breaking the logic into functions or using switch where possible.
  • Use Functions: For complex conditions putting code into functions can simplify logic and make it easier to read.
  • Don’t Forget break in switch Statements: Missing break can lead to unintended behavior by letting code run into the next case.

These little tricks will keep your conditionals manageable making your code easier to follow and debug.

Conditionals are all about practice. Try writing a simple program to make decisions based on different scenarios like suggesting activities based on weather or choosing different greetings for different times of day. With a little experimentation you’ll find that conditionals are actually easy!

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.