String.Empty in Switch/case statement generate a compiler error
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.