C # - A NULL object occupies memory?


Could someone tell me if a NULL object occupies memory?

I have the following Scenario, I have a class A , B and C , and class B and C is inside the class A , then how would the memory be in these 3 scenarios ?

1. ClassC C = null;

2. ClassA A = new ClassA()
  A.B = new ClassB();
  A.C = null;

3. ClassA A = null;

In those 3 scenarios, how is memory allocation? if it is NULL, does it not use memory? or how those scenarios are handled internally.

asked by RSillerico 09.12.2016 в 21:53

1 answer


null is not an object ... it is a value that tells you that there is no object.

If you write:

ClassC C = null;

You'll get an error NullReferenceException .

Now, when you say:

ClassA a1 = new ClassA();

There are two types of memory involved in your code. There is the object that was created by calling the constructor ClassA , and there is the variable a1 , which stores a reference to that new object.

Then, to answer your question, the null value does not refer to any memory , but the variables that have that value, will always occupy some memory. For example, in a 32 bit processor, the variable a1 would occupy 4 bytes (32 bit) of memory, it does not matter if it is referencing null, or a valid object.

answered by 09.12.2016 / 22:39