5

All object references in .NET are basically 32-bit or 64-bit pointers.
I am curious about how null is represented in memory. Is it actually 32 or 64 zeroes? Is it guaranteed to be so, according to specification?

I couldn't find the answer on MSDN or C# language specification.
There is also a similar question for C language, but what about C#?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • Just to add a comment on `Is it guaranteed to be so, according to specification?` Even if it where, (since thebjorn's answer implicitly suggest it isn't), typical behavior of memory management results in shifting pointer addresses. So relying on a fixed value, even for `null` is potentially dangerous. – Stefan Aug 13 '18 at 11:56
  • 1
    [A pointer with value `null` is represented by all-bits-zero](https://docs.microsoft.com/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-types). The spec says nothing about *references* with value `null` because it doesn't have to -- there's no (safe, portable, managed) way to interpret a reference as its bit representation. Having said that, in practice it *is* represented as all-bits-zero; any implementation that didn't do this would have a lot of hoops to jump through on the IL level. Tellingly, `brfalse`, `brnull` and `brzero` are all aliases for the same thing. – Jeroen Mostert Aug 13 '18 at 12:01

2 Answers2

3

I couldn't find the answer on MSDN or C# language specification.

Bacause it does not matter. As you never can work with the pointer - this is an implementation detail.

You can check the CLR sources at https://github.com/dotnet/coreclr

THAT SAID - I think it is all 0 because when laoding that into a register, there should be (at least it was wehen i learned assembler) a special flag that the value is null, so the check is super fast.

TomTom
  • 61,059
  • 10
  • 88
  • 148
2

It seems it would be convenient for an implementation to implement the null reference as all-bits-zero according to the language spec: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#default-values

thebjorn
  • 26,297
  • 11
  • 96
  • 138