Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is null represented in .NET

Tags:

.net

null

memory

I was having a conversation with a co-worker and the subject of null came up. He was telling me that in .NET behind the scenes it is just a really small number. I always thought that the object just didn't have a pointer to any memory on the heap but i wasn't sure either way.

So i'm hoping the community can clear it up for us ;P

like image 988
Alex Avatar asked Dec 29 '08 22:12

Alex


2 Answers

It's 0.

Snip from ldnull in ECMA-335 spec:

It might be thought that ldnull is redundant: why not use ldc.i4.0 or ldc.i8.0 instead? The answer is that ldnull provides a size-agnostic null – analogous to an ldc.i instruction, which does not exist. However, even if CIL were to include an ldc.i instruction it would still benefit verification algorithms to retain the ldnull instruction because it makes type tracking easier.

like image 181
leppie Avatar answered Nov 08 '22 21:11

leppie


When a nullable type instance is set to null, its underlying value is zero.

To be more specific, a nullable type is a structure that combines a value of the underlying type together with a boolean null indicator. An instance of a nullable type has two public read-only properties: HasValue of type bool, and Value of the nullable type’s underlying type.

HasValue is true for a non-null instance and false for a null instance.

So when HasValue is true, the Value property returns the contained value. When HasValue is false, an attempt to access the Value property throws an exception. But if you could access it, you would find it contains zero.

like image 27
HTTP 410 Avatar answered Nov 08 '22 20:11

HTTP 410