Alexandre
Alexandre

Reputation: 13308

Reference types

 var a = MyClassInstance;
    MyClassInstance = null;
    //if (a !=null){ //why }

I think that a points to MyClassInstance and MyClassInstance equals null, then a must be equals null too. But a is not null and I don't understand why.

Upvotes: 6

Views: 104

Answers (4)

Kelon
Kelon

Reputation: 851

The variable of a reference type instance is mainly a pointer to a memory address - so your example is comparable to

int MyClassInstance = 0x1234; // points to a memory containing *your* values
int i = MyClassInstance;
MyClassInstance = 0x0;
if (i !=0x0){ //still 0x1234, because it's a copy }

Or in other words: the variable is the reference, not the object itself. So the second variable is a copy of the reference.

Upvotes: 2

SirViver
SirViver

Reputation: 2441

Because you are assigning null to the variable MyClassInstance which just referenced your actual instance located on the heap. You do not touch your actual class instance in any way.

In fact, you cannot directly free the memory your class instance occupies; this is what the garbage collector is for. It looks if there are any references (think pointers, but not) to your instance left, and if none remain, the object is deleted/collected from memory.

Maybe this makes it clearer: http://en.csharp-online.net/Value_vs_Reference

Upvotes: 2

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The variable a is a reference, so the value it holds is the "location" of some object. MyClassInstance is also a reference. By setting a = MyClassInstance they both point to the same instance. Setting MyClassInstance to null affects that reference only. It doesn't affect the object itself and it doesn't affect any other references.

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

a and MyClassInstance are references to an object.
Changing one reference doesn't change the other.

var a = MyClassInstance; // Both references point to the same object
MyClassInstance = null;  // MyClassInstance now points to null, a is not affected

Upvotes: 5

Related Questions