Skip to main content
Published on

Switch in C#

Share:

Introduction

Decision-making is a fundamental part of programming. In C#, in addition to the traditional use of if and else, the switch presents an effective alternative for handling multiple conditions based on equality.

What is the Switch?

The switch in C# is a control structure that allows you to execute different blocks of code depending on the value of a variable or expression.

Advantages of Using Switch

  1. Clarity: Makes the code easier to read compared to multiple if-else chains.
  2. Organization: Keeps the code well-structured, especially useful when there are many conditions.
  3. Efficiency: In some situations, it can be more efficient than if-else by optimizing case selection.

Limitations

  • Equality: The switch can only check for equality, making it unsuitable for complex comparisons.
  • Data Types: Limited to certain data types, such as int, char, string, among others.

Usage Example

Consider the following example that illustrates the basic use of switch:

using System;

namespace Base {
  class Switch {
    public void Run() {
      char caseValue = 'D';

      switch (caseValue) {
        case 'A':
          Console.WriteLine("Case A exists.");
          break;
        case 'B':
          Console.WriteLine("Case B exists.");
          break;
        case 'C':
          Console.WriteLine("Case C exists.");
          break;
        default:
          Console.WriteLine($"Case {caseValue} does not exist.");
          break;
      }
    }
  }
}

// Case D does not exist.

Practical Tips

  • Use switch when you have a limited and well-defined set of possible values.
  • Prefer if-else for conditions involving logical comparisons or ranges.
  • Always include a default case to handle unexpected values.

Conclusion

The switch is a valuable tool in C# for simplifying decision-making based on multiple possibilities. Although it has its limitations, when used appropriately it can make code clearer and more organized.

Happy coding!