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;
            }
                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.
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.
No you can't.
Since null has no type, and is not an instance of anything, it will not work with a switch statement.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With