Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't String.Empty be used when creating a const string variable?

Tags:

c#

I often use String.Empty for a placeholder, which equates to "". So my question, why does a const not like String.Empty? They compile identically.

// Good
private const string example = "";

// Bad
private const string example = String.Empty;

What in String.Empty makes it not able to be used with a const.

like image 437
Greg Avatar asked Jan 06 '23 13:01

Greg


1 Answers

String.Empty is not a constant it's only readonly field. And since it's readonly field (which is not known on compile time) it can't be assigned to a constant.

http://referencesource.microsoft.com/#mscorlib/system/string.cs,c9f70a27facb27cf

...
//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;
like image 78
Dmitry Bychenko Avatar answered Jan 22 '23 12:01

Dmitry Bychenko