13.6 The using Statement

Typically resource-release code should be placed in a finally block to ensure that a resource is released, regardless of whether there were exceptions when the resource was used in the corresponding try block. An alternative notation—the using statement (not to be confused with the using directive for using namespaces)—simplifies writing code in which you obtain a resource, use the resource in a try block and release the resource in a corresponding finally block. For example, a file-processing app (Chapter 17) could process a file with a using statement to ensure that the file is closed properly when it’s no longer needed. The resource must be an object that implements the IDisposable interface and therefore has a Dispose method. The general form of a using statement is


using (var exampleObject = new ExampleClass())
{
   exampleObject.SomeMethod(); // do something with exampleObject
}

where ExampleClass is a class that implements the IDisposable interface. This code creates an object of type ExampleClass and uses it in a statement, then calls its Dispose method to release any resources used by the object. The using statement implicitly places the code in its body in a try block with a corresponding finally block that calls the object’s Dispose method. For instance, the preceding brief code segment is equivalent to


                       {
                            var exampleObject = new ExampleClass();
                            try
                            {
                               exampleObject.SomeMethod();
                            }
                            finally
                            {
                               if (exampleObject != null)
                               {
                                  exampleObject.Dispose();
                               }
                            }
                       }

The if statement in the finally block ensures that exampleObject is not null—that is, it references an object—otherwise, a NullReferenceException would occur when attempting to call Dispose. Section 13.9 introduces C# 6’s new ?. operator, which can be used to express the above if statement more elegantly as a single line of code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset