Every once and a while, I have to get the basics to a language after long coding excursions. In VB.Net, I understand declarying a variable as an object type more or less creates a reference to it.
Take the following code:
Dim obj1 as Object
Dim obj2 as Object
obj1 = new Object
obj2 = new Object
obj1 = obj2
A very elementary set of tasks, but I am trying to figure out what exactly is going each step of the way. This is my understanding: Line 1, obj1 is declared as an Object type and the compiler creates a reference for obj1 to hold, but what is obj1 referencing at the end of line 1?(are nothing and null synonymous?) Line 2 is the same as line 1 except its a different variable. Line 3, the compiler allocates space in the heap for a new object and passes the reference to obj1 1 to hold. Line 4 is the same as line 3. The part that I’ve never been quite clear on is the the 5th line. obj1 is assigned to the same reference as obj2 so they are both pointing the same object in memory. So what happens to the object that obj1 was originally assigned in line 3? Once obj1 takes the same reference as obj2, does that leave the first new object left in memory with no way to access it (or at least until garbage collection starts)?
In VB parlance it’s pointing to
Nothing, which is the same as C#’snull(which in this instance you can think of as pointing to memory location zero).Yes, that’s exactly what happens. With the vagaries of garbage collection, you can never tell when this will actually be collected, and indeed, there is no guarantee that it will ever be collected.
Let the GC worry about that sort of stuff, don’t try to “help” it, unless you really (and dude I seriously mean really) need to.