c sharp

How to Properly Dispose Objects in C#

Due to the nature of C#, most of us hardly think about disposing objects. This is because C# has an incredibly powerful garbage collector that takes care of these problems for us.

However, if you are dealing with unmanaged resources, you might need to explicitly dispose these objects and free the available resources.

In this tutorial, we will learn how to properly dispose the objects by working with the C# “using” statement and the IDisposable interface.

C# IDisposable

Before we dive into the usage of the “using” statement, let us first try and understand the IDisposable interface.

In C#, any class that implements the IDisposable interface have a “Dispose” method that is responsible for releasing resources such as files, database connections, network sockets, and more.

The following shows a basic class that implements the IDisposable interface:

class DisposableResource: IDisposable
{
    // Constructor, members, etc
    public void Dispose()
    {
        // Release unmanaged resources here
    }
}

Once the object goes out of scope, the “Dispose” method is called explicitly to release the resources. It is also recommended to keep in mind that this method is also called when an exception occurs when using the resource.

The following example shows how to use the “using” keyword for resource management:

using System;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {
        var path = "hello.txt";
        using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
        using var sr = new StreamReader(fs, Encoding.UTF8);
        string content = sr.ReadToEnd();
        Console.WriteLine(content);
    }
}

In the given example, we use the FileStream and StreamReader to read a text file from the file system.

Both the FileSsystem and StreamReader inherit the IDisposable interface. Hence, using the “using” statement, we ensure that the resources are released when the two objects are out of scope.

Instead of manually calling the “Dispose” method, C# provides a simple and intuitive method of reading a file. This automatically calls the “Dispose” method as follows:

using System.Text;

var path = "hello.txt";

string content = File.ReadAllText(path, Encoding.UTF8);

Console.WriteLine(content);

In this case, the ReadAllText method opens the specified file, reads the contents into a string, and then closes the file.

The Dispose Method

The second method of disposing the objects in C# is using the “Dispose” method. It allows us to explicitly release the unmanaged resources.

public class ResourceHolder : IDisposable
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
               // releases resources
            }

            // release resources
            disposed = true;
        }
    }

    ~ResourceHolder()
    {
        Dispose(false);
    }
}

In this example, we create a class called ResourceHolder that implements the IDisposable interface. We then override the “Dispose” method to release the resource explicitly.

We then use the disposed field to track whether the resources have been released to prevent it from releasing them multiple times.

Conclusion

In this tutorial, we discussed how to properly use the disposed objects in C# using the “Dispose” method.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list