C# Disposable Objects


This entry is part 2 of 8 in the series C# Interfaces

What are disposable objects?

The book C# 5.0 In A Nutshell, The Difinitive Reference published by O’REILLY written by Joseph Albahari and Ben Albahari says: “Some objects require explicit teardown code to release resources such as open files, locks, operating system handles, and unmanaged objects. In .NET parlance, this is called disposal, and it is supported through the IDisposable interface. The managed memory occupied by unused objects must also be reclaimed at some point; this function is known as garbage collection and is performed by the CLR.”

They go on to say: “Disposal differs from garbage collection in that disposal is usually explicitly instigated; garbage collection is totally automatic. In other words, the programmer takes care of such things as releasing file handles, locks, and operating system resources while the CLR takes care of releasing memory.”

One interface of particular interest is IDisposable. An object that supports the IDisposable interface must implement the Dispose() method — that is, it must provide code for this method.

Where this comes into play is when you are working in ASP.NET and you are adding a form. You use HTML helper methods, such as HTML.BeginForm(). A form is a container that we add various elements to. The BeginForm() method returns a disposable object. So we can wrap this call in a using block. At the end of the using block, the object returned from HTML.BeginForm() will be disposed. In the Dispose() method it will simply render the closing HTML tag we need to close off the form: </form>.

Manually

Our class DisposableDemoClass implements IDisposable. This obligates us to provide the Dispose() method in our code, which we do.

using System;
class DisposableDemoClass : IDisposable
{
        public string MyString = "hi there";
	public void Dispose()
	{
		Console.WriteLine("Dispose called! Yipee!");
	}
}
class Hello 
{
    static void Main() 
    {
		var disp = new DisposableDemoClass();
		Console.WriteLine(disp.MyString);
		disp.Dispose();
    }
}

Using Block

Below we employ the using code block so that the Dispose() method is called automatically.

using System;
class DisposableDemoClass : IDisposable
{
    public string MyString = "hi there";
	public void Dispose()
	{
		Console.WriteLine("Dispose called!");
	}
}
class Hello 
{
    static void Main() 
    {
		using(var disp = new DisposableDemoClass())
		{
		    Console.WriteLine(disp.MyString);
		    Console.WriteLine("Hello");
		}
    }
}

Both the Pocket Reference and the Nutshell books rate highly over at BookAuthority.

Series Navigation<< C# Interfaces IntroductionC# Interfaces Testability >>