Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can string.Empty ever be equal to null?

Tags:

string

c#

I was discovering a open source operating system's code that has been written in C#, and I saw the following check:

if (String.Empty == null)
     throw new Exception("Compiler didn't initialize System.String.Empty!");

It looked like a meaningless check to me but since I saw it in the source code of an operating system, I thought I may be missing something. Is there any chance that string.Empty can be null ?

Note: Here is the source code if you are interested to see

like image 830
Selman Genç Avatar asked Dec 20 '22 12:12

Selman Genç


1 Answers

According to MSDN:

String .Empty == ""

From referencesource.microsoft.com:

// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
. . . .
public static readonly String Empty;

(EE perhaps means "Execution Engine".)

Of course, it could be that some CLR implementations do not follow this rule, or someone managed to break it using Reflection. But if we consider such cases, then the answer should be close to "everything is possible".

like image 101
AlexD Avatar answered Jan 06 '23 08:01

AlexD