Link Types

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

I think a points to MyClassInstance , and MyClassInstance is null, then a should be null too. But a not null, and I do not understand why.

+6
source share
4 answers

The variable a is a reference, therefore its value is the "location" of any object. MyClassInstance also a link. By setting a = MyClassInstance , they both point to the same instance. Setting MyClassInstance to null only affects this link. It does not affect the object itself and does not affect other links.

+4
source

a and MyClassInstance are object references.
Changing one link does not change another.

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

Since you are assigning null to the MyClassInstance variable, which simply refers to your actual instance located on the heap. You do not touch your actual instance of the class in any way.

In fact, you cannot directly free the memory that your instance of the class occupies; This is what the garbage collector does. It looks if there are any links (I think, pointers, but not) to your instance on the left, and if there are none left, the object will be deleted / collected from memory.

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

+2
source

An instance variable of a reference type 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 a copy } 

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

+2
source

Source: https://habr.com/ru/post/888190/


All Articles