C#.NET — Validity of case labels in switch with variables. int i, j, id = 0; switch (id) { case i: Console.WriteLine("I am in Case i"); break; case j: Console.WriteLine("I am in Case j"); break; }

Difficulty: Easy

Correct Answer: The compiler will report case i and case j as errors since variables cannot be used in cases.

Explanation:


Introduction / Context:
This question checks the requirement that C# switch case labels be compile-time constants, not variables whose values are only known at runtime.


Given Data / Assumptions:

  • Switch discriminant: id (an int).
  • Case labels: i and j, both variables.


Concept / Approach:
In C#, case labels must be constant expressions (e.g., literals, const fields, or enum members). Using non-const variables as case labels is a compile-time error.


Step-by-Step Solution:

Identify the nature of case labels: i and j are plain int variables, not const. C# requires "case <constant>" for each label. Therefore, the compiler flags both case i and case j as errors.


Verification / Alternative check:
Replace i or j with const int K = 5; case K: ... and the code would compile. Similarly, enum members are allowed because they are constants.


Why Other Options Are Wrong:

  • No default case is not itself an error.
  • Printing "I am in Case i" or "Case j" cannot occur because compilation fails.
  • "There is no error" contradicts the language rule.


Common Pitfalls:
Confusing switch-case rules from other languages or assuming any expression is permitted in labels. C# enforces constants for determinism at compile time.


Final Answer:
The compiler will report case i and case j as errors since variables cannot be used in cases.

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion