String.Empty in a Switch / case expression generates a compiler error

If String.Empty is as good as "" , then where does the compiler toss the .Empty string in the case ? In my opinion, nothing can be more permanent than String.Empty . Somebody knows? Thank you

 switch (filter) { case string.Empty: // Compiler error "A constant value is expected" break; case "": // It Okay. break; } 
+5
source share
2 answers

Instead, you can try:

 switch(filter ?? String.Empty) 

string.Empty is a read-only field, while "" is a compile-time constant. You can also read the article here in the 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 problem when you provide a default parameter value inside your method (C # 4.0):

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

The above will result in a compile-time error, since the default value must be constant.

+6
source

The reason is that you cannot use readonly -only values ​​in the 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 equivalent to "" , here I can prove it with the same switch statement example:

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

Then the only reason it does not allow string.Empty is if it is string.Empty read-only, the switch will not allow read-only values ​​in its case.

+3
source

Source: https://habr.com/ru/post/1232502/


All Articles