Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference types

Tags:

.net

 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.

like image 379
Alexandre Avatar asked May 16 '11 08:05

Alexandre


2 Answers

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
like image 123
Daniel Hilgarth Avatar answered Sep 18 '22 22:09

Daniel Hilgarth


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.

like image 29
Brian Rasmussen Avatar answered Sep 18 '22 22:09

Brian Rasmussen