6

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;

            }
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Zuzlx
  • 1,246
  • 14
  • 33

2 Answers2

6

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.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Thanks Rahul. But I was just wondering how come we can't use string.Empty. It's kind of strange to me. – Zuzlx Sep 29 '15 at 05:50
  • @Zuzlx:- As far as I know `string.Empty` is a read-only field whereas `""` is a compile time constant. – Rahul Tripathi Sep 29 '15 at 05:51
  • Makes sense. Thanks again. We can discover that there is water on Mars but jolly we can't use `string.Empty` testing for for `""` Sad state of affairs – Zuzlx Sep 29 '15 at 05:54
4

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.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88