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 Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac 13 min read AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of 4 min read CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi 6 min read Like