C# Using

Using keyword

The using block helps manage resources. Conceptually it protects the whole system's resources by specifying the scope of the usage of the resource. The using statement is combined with a type that implements IDisposable.

Keywords

Example

Main method

To begin, this little program defines a class called SystemResource. The class implements the IDisposable interface and the required Dispose method. In the Main method, we wrap the SystemResource instance inside a using statement.

Program that demonstrates using statement: C#

using System;
using System.Text;

class Program
{
    static void Main()
    {
	// Use using statement with class that implements Dispose.
	using (SystemResource resource = new SystemResource())
	{
	    Console.WriteLine(1);
	}
	Console.WriteLine(2);
    }
}

class SystemResource : IDisposable
{
    public void Dispose()
    {
	// The implementation of this method not described here.
	// ... For now, just report the call.
	Console.WriteLine(0);
    }
}

Output

1
0
2
Question

What happens when the program executes? First, the SystemResource instance is allocated upon the managed heap. Next, the "1" is written. Third, the "0" is written because the Dispose method is invoked. And finally, the "2" is printed.

Then:As demonstrated, the Dispose method is called immediately when control flow exits the using block.

Example 2

Programming tip

It is possible to nest multiple using statements one after another. You do not need to use any curly brackets in this case. In the second or further using statements, you can use the variables declared in previous using statements as well.

Program that nests using blocks: C#

using System;

class Program
{
    static void Main()
    {
	using (SystemResource resource1 = new SystemResource())
	using (SystemResource resource2 = new SystemResource())
	{
	    Console.WriteLine(1);
	}
    }
}

class SystemResource : IDisposable
{
    public void Dispose()
    {
	Console.WriteLine(0);
    }
}

Discussion

Logo

It is most common to use using with types that are already defined in the .NET Framework. Some of these types include StreamReader, StreamWriter, BinaryReader, BinaryWriter, or even DataTable.

StreamReaderStreamWriterBinaryReaderBinaryWriterDataTable

To do this, simply use the resource acquisition expression for the type inside the using statement. You do not need to implement any interfaces. Many types implement already the Dispose method.

Summary

C# programming language

The using statement provides a syntactic sugar for invoking the Dispose method found in the IDisposable interface implementation. This article does not describe a useful implementation of Dispose.

Review:The using statement interacts with Dispose. It affects the path of the control flow in the virtual execution engine.

Syntactic Sugar: Programming Term

C#: .NET