Can string.Empty be null?

I discovered the open source operating system code 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 pointless check for me, but since I saw it in the source code of the operating system, I thought maybe something was missing. Is there a chance that it string.Emptycould be zero?

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

+4
source share
5 answers

Could it be? Yes.

Will it tell you that this is a line of code? Not reliable. Once you break runtime invariants, the behavior of all code becomes unreliable.

, , , :

if (ReferenceEquals(null, typeof(string).GetField("Empty").GetValue(null)))
+3

MSDN:

String .Empty == ""

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, , " ".)

, , CLR , - Reflection. , " ".

+4

(, , ) ( -, ), String.Empty "".

, (AtomOS), IL2CPU, IL , IL2CPU.

+2

no, string.Empty .

, , # . , unit test, .

+1

In a normal no application, String.Empty can never be null.

The exception message seems to suggest that the compiler is the one that initializes String.Empty for AtomOS, although that doesn't make sense ... String.Empty is initialized with a static constructor at runtime, not at compile time .

I don't know if it is possible that String.Empty is null in AtomOS, but in general this is not possible if the runtime or implementation of System.String does not work.

+1
source

All Articles