using Statement (C# Reference)

Provides a convenient syntax that ensures the correct use of IDisposable objects.


The following example shows how to use the using statement.

using (Font font1 = new Font("Arial", 10.0f)) 
    byte charset = font1.GdiCharSet;


File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in the using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs within the using block. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

  Font font1 = new Font("Arial", 10.0f);
    byte charset = font1.GdiCharSet;
    if (font1 != null)

For more information about the try-finally statement, see the try-finally topic.

Multiple instances of a type can be declared in the using statement, as shown in the following example:

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
    // Use font3 and font4.

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, after control leaves the using block, the object remains in scope but probably has no access to its unmanaged resources. In other words, it's not fully initialized anymore. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it's generally better to instantiate the object in the using statement and limit its scope to the using block.

Font font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
    // use font2
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight(); 

For more information about disposing of IDisposable objects, see Using objects that implement IDisposable.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

C# Reference
C# Programming Guide
C# Keywords
using Directive
Garbage Collection
Using objects that implement IDisposable
IDisposable interface