I'm refining my code and noticed that at some places I had optional parameters with the default value of an empty string. I changed that to a default value from the class for empty string and guess what! Apparently there's a difference between empty quotation marks and string.Empty
. What the duck?! (typo intended)
private void Khaboom(String parameter = "") { ... }
private void Bazinga(String parameter = String.Empty) { ... }
Can someone explain to me why the duck does Khaboom
work while Bazinga
doesn't?!
The error message whines this:
Default parameter value for 'parameter' must be a compile-time constant.
Well... It is!
Because String is a class and therefore cannot be a constant.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.
In application code, this field is most commonly used in assignments to initialize a string variable to an empty string. To test whether the value of a string is either null or String. Empty, use the IsNullOrEmpty method.
Empty
is defined as follows:
public static readonly string Empty
It's not a constant. It's a readonly field.
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