IDisposable Interface
Make unmanaged resources easily releasable in user-defined types.
We'll cover the following...
Usage
The goal of the IDisposable
interface is to provide a uniform way to work with objects that interact with unmanaged resources (like files, database connections, and so on). The IDisposable
interface declares a single Dispose()
method, in which unmanaged resources must be released:
Press + to interact
Program.cs
Course.cs
using System;namespace GarbageCollector{class Program{static void Main(string[] args){// Suppose we create an object that uses unmanaged resourcesvar course = new Course() { Title = ".NET Fundamentals" };// After we are done using it, we should make sure that// unmanaged resources are released:course.Dispose();}}}
For demonstration purposes, our Dispose()
implementation only holds one Console.WriteLine()
statement. In real apps, the Dispose()
method must contain logic that safely clears the resources used by the object (open file, database connection).
In the example above, We call our Course
object’s Dispose() method after we use it… While this is a viable approach in our example, ...