It’s easier to ask the question after showing an example…
MyClass a = new MyClass();
a.initializeData();
a = new MyClass();
After allocating space for a new MyClass, what happens to my previous allocation? Does the garbage collector automatically collect it because I know there’s no delete in C#
I just want to make sure I’m not going to have any memory leaks.
Thanks!
First, it’s called “creating an object”, not “reallocating a class”.
The entire idea of garbage collection is that you don’t care what happens to objects on which you have no reference: you code as if there was infinite memory (within reason). The purpose of the garbage collector is not to free memory for you, it is to simulate that there is an infinite amount of memory.
It just so happens that in order to do this, the garbage collector might reclaim previously allocated memory on which you hold no reference from time to time; it might also reorganize the used memory to prevent fragmentation, and update all your references to point towards new memory locations. All of this is implementation details that you shouldn’t be concerned with.
Of course, it’s very interesting to learn how the GC works. 🙂