Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Empty in Switch/case statement generate a compiler error

If String.Empty is as good as "", then how come the compiler throws up with string.Empty in the case statement? Nothing can be more constant than string.Empty in my view. Anyone know? Thanks!

switch (filter)
            {
     case string.Empty:  // Compiler error "A constant value is expected"

                break;

                case "":  // It's Okay.
                    break;

            }
like image 677
Zuzlx Avatar asked Sep 29 '15 05:09

Zuzlx


People also ask

Can I use string in switch-case?

It is recommended to use String values in a switch statement if the data you are dealing with is also Strings. The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time). Comparison of Strings in switch statement is case sensitive.

Should I use string empty C#?

Empty . The first uses the C# language keyword string so it always works. The latter only works with using System; in the file. Prefer string over String always.

Can we use string in switch-case in C?

No you can't.

Does switch support null in Java?

Since null has no type, and is not an instance of anything, it will not work with a switch statement.


2 Answers

You can try like this instead:

switch(filter ?? String.Empty)

string.Empty is a read-only field whereas "" is a compile time constant. You can also go through a article here on Code Project String.Empty Internals

//The Empty constant holds the empty string value.
//We need to call the String constructor so that the compiler doesn't
//mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field 
//which we can access from native.

public static readonly String Empty = ""; 

On a side note:

You will also see this issue when you are providing the default parameter value inside your method(C# 4.0):

void myMethod(string filter = string.Empty){}

The above will result in a compile time error as the default value needs to be a constant.

like image 173
Rahul Tripathi Avatar answered Nov 14 '22 21:11

Rahul Tripathi


The reason is: you cannot use readonly values in case: consider the following scenario:

public string MyProperty { get; } // is a read-only property of my class
switch (filter)
{
    case MyProperty:  // wont compile this since it is read only
    break;
          // rest of statements in Switch
}

As you said string.Empty is equivalent to "", here I can prove this with the same example of a switch statement:

string filter = string.Empty;
switch (filter)
{
   case "":  // It's Okay.
   break;
    //rest of  statements in Switch
}

Then the only reason it won't allow string.Empty in case it is read-only, the switch won't allow read-only values in its case.

like image 42
sujith karivelil Avatar answered Nov 14 '22 21:11

sujith karivelil