Is it possible to check for null values in switch case statement in C#

Viewed 701

I have an object with the property Value. Value is a nullable number. I have some scenarios for the value of value. Usually, for null cases, I use the default case but this time, it is not correct logically. I want to do "X" in case of 100, "Y" in case of no value (the value is null), otherwise, I want to do "Z".

switch (p.Value)
{
    case 100:
        // DO X
        break;
    default:
        // Do Z
        break;
}

I tried writing case is null but it doesn't compile: Invalid expression term 'is' (CS1525). Is it possible or should I use if statements instead?

2 Answers

Just tryed it

void Main()
{
    int? p=null;
    
    switch (p)
    {
        case   null:
        
        break;
        
        case 100:
            // DO X
            break;
        default:
            // Do Z
            break;
    }
}

everything works fine

You can check for null in a switch case, just like any other value, but you can't use is, is is used in casting

switch (p.Value)
      {
        case 100:
            // DO X
        case null:
            // DO Y
            break;
        default:
            // Do Z
            break;
  }

Anyway a case where the item is null is only 1 case, therefore you can just check it with an if statement that is warpped around the switch

In your case

if (p.Value == null){
  //DO Y;
}else{
  switch (p.Value)
  {
    case 100:
        // DO X
        break;
    default:
        // Do Z
        break;
  }
}

The first option is much cleaner, and you should choose it

Related