using Statement in C#

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object


Example:

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

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.

{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}

Multiple instances of a type can be declared in a using statement.

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

No comments:

Post a Comment