C# Switch with String.IsNullOrEmpty

maxfridbe picture maxfridbe · Jan 11, 2009 · Viewed 19.9k times · Source

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

Answer

Maxime Rouiller picture Maxime Rouiller · Jan 11, 2009

I would suggest something like the following:

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

Is that what you are looking for?