I am sort of new to C# and I have a quick question about instances of classes.
I was told that using only "null"on an instance of a class isn't enough to delete an entire instance and all it's resources, such as pointers, etc. So I have:
ClassHere myClass = new ClassHere()
and myClass = null
I really must be thinking about this too hard... I'll give an example as to figure out how exactly the GC works.
Let's say we have 3 instances: x1, x2, x3. Each instance would be mapped to a variable: ClassHere myClass = new ClassHere()
except you'd have x1, x2 and x3 instead of myClass.
Then say instances x2 and x3 make some sort of reference to x1. Let's say that x1 does nothing after being referenced by x2 and x3. The GC would only pick up x1 after x2's, and x3's references of x1 would be removed, correct?
If it picks it up even with those references. How would the GC know whether or not I actually need instance x1 which is referenced by x2 and x3 instead of deleting it?
Or am I missing something here?
Well, the only way to destroy a class is to remove it from your source tree :D You can, though destroy instances of a class.
Unlike C++, C# doesn't have deterministic destructors. An object instance becomes eligible for garbage collection when the object instance becomes unreachable. That can happen by virtue of
When and if an object instance is garbage-collected depends on memory/resource pressure within the app domain (process). When the app domain ends, though, everything is garbage collected.
Usually you want to make things that matter implement IDisposable
, so non-managed resources held can be deterministically released via using
blocks and the like.
This is a simplistic answer, but the gist of it is: don't sweat it.