Using (special use in C-Sharp)

From eqqon

Jump to: navigation, search

Apart from including namespaces in C# the keyword using is also overloaded with another meaning related to IDisposable.

interface IDisposable

Objects that implement IDisposable can be used in the using statement. After the block ends, the object's Dispose-method is guaranteed to be called. Note: The object's destructor is not guaranteed to be called immediately.

Example

using System;

public class Resource : IDisposable
{
	public void Dispose() 
	{
		Console.WriteLine("Disposed");
	}
	~Resource() {
		Console.WriteLine("~Resource");
	}
}

public class Program 
{
	public static void Main() 
	{
		using( Resource h = new Resource()) {
			Console.WriteLine("Inside using block");
		}
		Console.WriteLine("After using block");
	}
}
Program output
Inside using block
Disposed
After using block
~Resource