Say I have the following class...
Class1
{
private ArrayList myList;
private Class1
{
// Here fill myList with a bunch of Foo objects.
}
public ArrayList GetList()
{
return myList;
}
}
Then say in some other class you have the following code...
Class1 myClass = new Class1();
Foo myFavoriteFoo = myClass.GetList()[0] As Foo;
Now, myFavoriteFoo is actually a reference to the Foo that exists in the arraylist in Class1. What will happen if something inside Class1 removes that specific Foo from the class or disposes of it? Will myFavoriteFoo immediately = null? I am guessing if I tried to access Foo.SomeMethod() I would just get an exception like "Object reference not set to an instance of an object"...
The answer is that it cannot happen.
dotNet offers type-safety: a reference always points to a valid instance or it is null, no other options. That is why there is no manual memory management in dotNet (no delete).
So if your code is holding a reference to an object somewhere then that reference blocks it from garbage collection.
And Dispose() is something else, it has nothing to do with the memory an object occupies. Dispose() is a cleanup for (unmanaged) resources and usually the object will set its internal state to IsDisposed=true ('invalid').
So you can Close (== Dispose) a FileStream. You then still have the object, it will just throw when you try to use it.
Reference objects will not be deleted while there are references pointing to them (with a few exceptions you don't have to worry about). When the original reference goes out of scope, the other reference will still point to your object, and the object will remain alive. After you drop the second reference (by setting it to null, assigning it a different value, or having it run out of scope), the GC may collect it (but isn't guaranteed to do so immediately).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With