Question

I read this documentation but I'm still confused.

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

In the code, does it mean that we are introducing a new instance of Font class called font1. However, this instance will be alive ONLY within the curly brackets. Further on in the code we can again instantiate font1 but that will be a completely different instance since the previous font1 was disposed.

Is this correct? Then what is the purpose? We could reassign different values to font1 without disposing the previous one?

Was it helpful?

Solution 2

The correct answer is the "using" keyword ensures that any IDisposible objects are properly disposed, even if an exception occurs.

Consider the following:

var f = File.Open("somepath");
f.Write(foo);
throw new Exception();
f.Close();
f.Dispose();

The file stream (a resource shared with other applications and the OS) is never properly closed in this case, which is a bad thing.

However, using the following approach:

using(var f = File.Open("somepath")){
    throw new Exception();
}

ensures that the file stream is closed even if an exception occurs inside the block. It is simply a shortcut to writing:

{
    FileStream f = File.Open("somepath");
    try{
        throw new Exception();
    }finally{
        f.Close();
    }
}

OTHER TIPS

The "using" syntax is just syntactic sugar. From the document you cite, it's shorthand for:

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

It's there to encourage you to use classes that must be disposed (i.e. implement IDisposable) correctly.

The most common purpose of the using statement is to ensure that the object we are "using" will be disposed of if an exception is thrown at any point within the using block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top