Garbage Collection (C# vs Java)
In C and C++, many objects require the programmer to allocate their resources once declared, before the objects can be safely used. Releasing these resources back to the free memory pool once the object has been used is also the responsibility of the programmer. If resources are not released, the code is said to leak memory, as more and more resources are consumed needlessly. On the other hand, if resources are released prematurely, loss of data, the corruption of other memory areas, and null pointer exceptions can occur.
Both Java and C# prevent these dangers by independently managing the lifetime of all objects in use by an application.
In Java, the JVM takes care of releasing unused memory by keeping track of the references to allocated resources. Whenever the JVM detects that a resource is no longer referenced by a valid reference, the resource is garbage-collected.
In C#, garbage collection is handled by the common language runtime (CLR) with similar functionality to that of the JVM. The CLR garbage collector periodically checks the memory heap for any unreferenced objects, and releases the resources held by these objects.