简体   繁体   中英

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

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

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)))

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM