Selman Genç
Selman Genç

Reputation: 101681

Can string.Empty ever be equal to null?

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

Upvotes: 4

Views: 286

Answers (5)

AlexD
AlexD

Reputation: 32566

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

Upvotes: 4

Max Truxa
Max Truxa

Reputation: 3478

In a normal environment this could (or better say should) never be the case (except for a bug in the runtime, or somebody messing around with reflection), since String.Empty is specified to be equal to "".

Since the project you are referring to (AtomOS) is using IL2CPU to translate the IL code to native machine instructions, this could maybe be used to catch a bug in IL2CPU.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283614

Can it? Yes.

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

This line is more likely to successfully perform the test, but still gives no guarantees:

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

Upvotes: 3

jstedfast
jstedfast

Reputation: 38528

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

The exception message seems to suggest that the developers think that the compiler is what initializes String.Empty for AtomOS, though, which makes no sense... String.Empty is initialized by the static constructor at runtime, not at compile time.

I don't know if it's possible for String.Empty to be null in AtomOS, but in general, it's not possible unless the runtime or implementation of System.String is buggy.

Upvotes: 1

David Crowell
David Crowell

Reputation: 3813

According to the standard, no, string.Empty should never be null.

However, this probably uses a custom C# compiler to write an OS. I would think this test would be better in a unit test, but that's just me.

Upvotes: 1

Related Questions