Skip to main content
Published on

if, else if and else in C#

Share:

Introduction

Decision-making is a fundamental part of programming. In C#, the if, else if and else conditional statements allow your program to make decisions based on certain conditions, directing the code flow as needed.

Basic Structure

Conditional statements are based on boolean evaluations: true or false. The basic structure starts with "if", followed by a condition. If that condition is true, the code inside the "if" block is executed.

if: The Initial Decision

The "if" statement evaluates a condition and, if that condition is true, executes the block of code that follows it.

else if: Additional Evaluations

When the "if" condition is not met, the program can check other conditions using "else if". The code inside an "else if" block is only executed if its condition is true and all previous "if" and "else if" conditions are false.

else: The Default Scenario

The "else" statement, which has no condition, serves as a default case. If none of the "if" or "else if" conditions are met, the code inside the "else" block is executed.

using System;

namespace Base {
  class IfElseIfAndElse {
    public void Run() {
      int x = 30;

      if (x == 10) {
        Console.WriteLine("The value of x is equal to 10.");
      }
      else if (x == 20) {
        Console.WriteLine("The value of x is equal to 20.");
      }
      else {
        Console.WriteLine("The value of x is different from 10 and 20.");
      }
    }
  }
}

// The value of x is different from 10 and 20.

Additional Considerations

Comparison Operators

Conditions frequently use comparison operators, such as:

  • == for equality
  • != for inequality
  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to

These operators allow you to evaluate the relationship between two values.

Combining Conditions

Using logical operators, such as && (AND) and || (OR), it is possible to combine multiple conditions, making the evaluation even more flexible.

Conclusion

The "if", "else if" and "else" conditional statements are fundamental for decision-making in C#. By fully understanding these statements, it is possible to create more dynamic and adaptive programs.

Happy coding!