We have learned in the previous section that object disposal in .NET Core is automatically done by the GC. Nevertheless, disposing of objects in your code is always a good practice, and is highly recommended when you are working with unmanaged objects. In this section, we will explore some best practices that can be used to dispose of objects while writing code in .NET Core.
IDisposable
is a simple interface that contains one Dispose
method, takes no parameter, and returns void
:
public interface IDisposable { void Dispose(); }
It is used to release unmanaged resources. So if any class implements the IDisposable
interface, it means that the class contains unmanaged resources and these have to be released by calling the Dispose
method of the class.