Question

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
Was it helpful?

Solution

I would suggest something like the following:

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

Is that what you are looking for?

OTHER TIPS

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.

how about

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

}

From the documentation of String.Empty:

The value of this field is the zero-length string, "".

I interpret this to mean that there is no difference between "" and String.Empty. Why are you trying to distinguish between them?

An empty string is "", which is equal to String.Empty. The reason that you can put "" in a case statement but not "String.Empty" is that "Empty" is a field of the class "String" and "" is actually a contant value.

Constant values are allowed in cases, String.Empty is a field and could be altered at run time. (In this case it will remain the same, but not all static fields of each class are constant values.)

In the case of 'if', that condition is evaluated at run time and if does not require a constant value.

I hope this explains why.

Something that I just noticed is that you can combine if/else and switch statements! Very useful when needing to check preconditions.

if (string.IsNullOrEmpty(text))
{
    //blah
}
else switch (text)
{
    case "hi":
        Console.WriteLine("How about a nice game of chess?");
        break;
    default:
        break;
}
string StrMode;
if (!string.IsNullOrEmpty(StrMode))
{  
    switch (StrMode.Trim())
    {
        case "Souse":
        {
             //Statement Eg:  
             MesssageBox.Show("Souse");
             break;
        }

        case "Company Agent":
        {
             //Statement Eg:
             MesssageBox.Show("Souse");
             break; 
        }

        default:
             return;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top