C#: What ‘null’ looks like in computer memory?

When you set a reference type to ‘null’ like this:

string str = null;

it means that it’s undefined. It’s not a zero or empty. It’s nothing. I wonder what nothing looks like inside of computer memory.

Let’s look under the hood of C#!

I Visual Studio we write a small Console App, set a breakpoint and run Debug

When Debug stops on the breakpoint we open Disassembly window

Okay. What we have here?

First, the line that defines ‘str1’ uses a real address in memory where the actual literal was created.

Second, the line that defines ‘str2’ uses ‘xor ecx,ecx’ to zero the ‘rcx’ register.

Except this, the two lines compile into almost the same code.

Conclusion:

A string is null when it references to zero address in memory.

Leave a Reply

Your email address will not be published. Required fields are marked *