Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch with String.IsNullOrEmpty

Is it possible to have a switch in C# which checks if the value is null or empty not "" but String.Empty? I know i can do this:

switch (text)
{
    case null:
    case "":
        break;
}

Is there something better, because I don't want to have a large list of IF statements?

I'mm trying to replace:

if (String.IsNullOrEmpty(text))
    blah;
else if (text = "hi")
    blah
like image 391
maxfridbe Avatar asked Jan 11 '09 01:01

maxfridbe


3 Answers

I would suggest something like the following:

switch(text ?? String.Empty)
{
    case "":
        break;
    case "hi":
        break;
}

Is that what you are looking for?

like image 190
Maxime Rouiller Avatar answered Sep 18 '22 13:09

Maxime Rouiller


What's wrong with your example switch statement?

switch (text)
{
    case null:
    case "":
        foo();
        break;
    case "hi":
        bar();
        break;
}

It works (and for some reason that surprised me - I thought it would complain or crash on the null case) and it's clear.

For that matter, why are you worried about String.Empty? I'm missing something here.

like image 44
Michael Burr Avatar answered Sep 19 '22 13:09

Michael Burr


how about

if (string.isNullOrEmpty(text))
{
   //blah
}
else
{
 switch (text)
 {
     case "hi":
 }

}

like image 35
JoshBerke Avatar answered Sep 20 '22 13:09

JoshBerke