Zuzlx
Zuzlx

Reputation: 1266

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;

            }

Upvotes: 7

Views: 2866

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29026

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.

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

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.

Upvotes: 6

Related Questions