Garbage collection in c#
You might have heard that c# and .net work in managed code environment, that means that .net provides automatic memory management for you. You as a programmer are not responsible for cleaning or freeing up the memory that your objects of classes use in course of running of the program.
Let us consider an example
MyClass object = new MyClass()
Here new indicates that it has allocated memory somewhere in the system, the framework takes care whether the object is no longer in use, and reclaims the memory for reuse in the system.
Let us see how this works
There is a big pool of memory available to the system, now your program is going to use the memory for the operation, now as the program runs, it allocates blocks of memory, and when it does that those blocks of memory will be taken from the system pool and assign to the program, at some point there is a special class in .net framework called “The Garbage Collector” and garabage collection is the process by which it figures out that memory is no longer being used by your programme and take it back into the system, so garbage collector has a way of keeping track of the objects that you allocate and figures out that these objects are no longer in use and simply puts back into the system’s memory pool, this process is completely invisible to your program.
Let us see how Garbage collection works
Let us consider a function below
and inside myfunc() we have got a new myobj
a block of memory is created that holds the object, now that allocated block is called a reference, that myobj variable created inside the function is reference to that memory location, you can do a lot of things inside a function you can call a method, set a property, you can also call another method, but when that function ends, myobj variable goes out of scope and there are no more references to myobj.
Things you should know about Garbage Collection
- Its not necessary for your program to initiate a garbage collection, though you can explicitly initiate garbage collection.
- Objects are not necessary claimed right away.
- Objects can detect that tey are about to be released from memory, there is an advanced method called a finalizer method.