The garbage collection provided by the .NET Framework is good enough when we are dealing with managed objects. However, there are several instances in which we need to use unmanaged resources in our code. Some of these instances include the following:
- When we need to access OS memory using pointers
- When we are doing I/O operations related to file objects
In each of these circumstances, the garbage collector does not explicitly free up the memory. We need to explicitly manage the release of such resources. If we do not release such resources, then we may end up with problems related to memory leaks in the application, locks on OS files, leaks on connection threads to resources such as databases, and more.
To avoid these situations, C# provides finalization. Finalization allows us to cleanup unmanaged code in a class before the garbage collector...