C# Program To Implement IDisposable Interface Last Updated : 28 Apr, 2025 Comments Improve Suggest changes Like Article Like Report IDisposable is an interface defined in the System namespace. It is used to release managed and unmanaged resources. Implementing IDisposable interface compels us to implement 2 methods and 1 boolean variable - Public Dispose() : This method will be called by the consumer of the object when resources are to be released. This method will invoke the Dispose(bool disposing) method. We also notify the Garbage collector(GC) about the current object’s resource cleaning so that GC avoids doing it again at the end.Protected virtual Dispose(bool disposing): This method is the place where all the variables will be set to null. Also the derived class can override this method and release its own resources. The actual resource cleaning code is written in this method.Bool disposedValue: To ensure the dispose method is called once we use a boolean variable. The resource cleaning must not happen more than once.The consumer of the object can call the first disposal method explicitly whenever the resources are no longer required. The garbage collector also cleans the object when it is out of scope. However, it is not capable of releasing a few objects such as files, streams, database connections, window handles, etc. Syntax:public interface IDisposable; Disposable Interface Key Points :The class implementing IDisposable interface must implement the dispose method. A class having unmanaged resources should implement IDisposable interface.The client or consumer of the object can call the disposal method explicitly when the object is no longer required.Whenever a disposal method is called we need to notify the garbage collector about it so that it ignores that object during the cleaning of objects afterward.If a class has a destructor, the only code in there should be an invocation of Dispose(false) to clean any unmanaged resources at the end.The disposal method should be called only once. To ensure that we use a boolean variable. If a base class is implementing IDisposable interface the derived classes should not implement the interface again.The Derived class can override the dispose(bool disposing) method and release its resources. Using Keyword:While we can call the Dispose method manually or we can use the Using keyword provided by C#. The Using keyword automatically calls the Dispose method when the scope of the variable is over. It plays a crucial role in improving the performance during garbage collection. Example 1: C# // Code Implementation of IDisposable interface in C# using System; namespace GFG { /// <summary> /// A File class which acts /// as an unmanaged data /// </summary> public class File { public string Name { get; set; } public File(string name) { this.Name = name; } } /// <summary> /// File Handler class which /// implements IDisposable /// interface /// </summary> public class FileHandler : IDisposable { // unmanaged object private File fileObject = null; // managed object private static int TotalFiles = 0; // boolean variable to ensure dispose // method executes only once private bool disposedValue; // Constructor public FileHandler(string fileName) { if (fileObject == null) { TotalFiles++; fileObject = new File(fileName); } } // Gets called by the below dispose method // resource cleaning happens here protected virtual void Dispose(bool disposing) { // check if already disposed if (!disposedValue) { if (disposing) { // free managed objects here TotalFiles = 0; } // free unmanaged objects here Console.WriteLine("The {0} has been disposed", fileObject.Name); fileObject = null; // set the bool value to true disposedValue = true; } } // The consumer object can call // the below dispose method public void Dispose() { // Invoke the above virtual // dispose(bool disposing) method Dispose(disposing : true); // Notify the garbage collector // about the cleaning event GC.SuppressFinalize(this); } // Get the details of the file object public void GetFileDetails() { Console.WriteLine( "{0} file has been successfully created.", fileObject.Name); } // Destructors should have the following // invocation in order to dispose // unmanaged objects at the end ~FileHandler() { Dispose(disposing : false); } } class Program { static void Main(string[] args) { Console.WriteLine( "Explicit calling of dispose method - "); Console.WriteLine(""); FileHandler filehandler = new FileHandler("GFG-1"); filehandler.GetFileDetails(); // manual calling filehandler.Dispose(); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine( "Implicit calling using 'Using' keyword - "); Console.WriteLine(""); using(FileHandler fileHandler2 = new FileHandler("GFG-2")) { fileHandler2.GetFileDetails(); // The dispose method is called automatically // by the using keyword at the end of scope } } } } Output: Comment More infoAdvertise with us Next Article C# Program To Implement IDisposable Interface B biswalashish1997 Follow Improve Article Tags : C# CSharp-Interfaces Similar Reads C# Program to Implement an Interface in a Structure Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. We can create a structure by using struct keyword. A structure can also hold co 2 min read C# Program to Implement Multiple Interfaces in the Same Class Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interfaceâs members will be given by the class that implements the interface implicitly or explicitly. C# allows that a sin 3 min read C# Program to Demonstrate Interface Implementation with Multi-level Inheritance Multilevel Inheritance is the process of extending parent classes to child classes in a level. In this type of inheritance, a child class will inherit a parent class, and as well as the child class also act as the parent class to other class which is created. For example, three classes called P, Q, 3 min read C Program to Implement Priority Queue Priority queue is an abstract data type(ADT) in the computer science which is designed to the operate much like the regular queue except that each element has the certain priority. The priority can determines the order in which elements are dequeued - elements with the higher priority are removed fr 6 min read Implement a Stack in C Programming Stack is the linear data structure that follows the Last in, First Out(LIFO) principle of data insertion and deletion. It means that the element that is inserted last will be the first one to be removed and the element that is inserted first will be removed at last. Think of it as the stack of plate 7 min read C# | Explicit Interface Implementation An Interface is a collection of loosely bound items that have a common functionality or attributes. Interfaces contain method signatures, properties, events etc. Interfaces are used so that one class or struct can implement multiple behaviors. C# doesn't support the concept of Multiple Inheritance b 4 min read C# Program to Implement the Same Method in Multiple Classes C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, Implement the same me 3 min read C Program to Implement Singly Linked List A linked list is a linear data structure used to store elements of the same data type but not in contiguous memory locations. It is a collection of nodes where each node contains a data field and a next pointer indicating the address of the next node. So only the current node in the list knows where 9 min read C# | How to Implement Multiple Interfaces Having Same Method Name Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface's members will be given by the class who implements the interface implicitly or explicitly. C# allows the impleme 4 min read C# - IDumpable Interface In this article, we will see how to implement IDumpable interface through C#. The IDumpable interface is just a simple interface which has a Dump() method and public property. Every class that wishes to implement the IDumpable interface has to implement the Dump() method and can make use of the publ 7 min read Like