Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use string.Empty as an optional parameter contrary to empty quotation marks? [duplicate]

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!

like image 296
Konrad Viltersten Avatar asked Jun 01 '14 22:06

Konrad Viltersten


People also ask

Why isn't string empty a constant?

Because String is a class and therefore cannot be a constant.

Is empty string same as?

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 .

Is null and empty string the same in C#?

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.

What is the use of string empty in C#?

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.


1 Answers

Empty is defined as follows:

public static readonly string Empty

It's not a constant. It's a readonly field.

like image 171
spender Avatar answered Sep 19 '22 06:09

spender