Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Using Objects That Encapsulate Resources

When you write code that uses an object that encapsulates a resource, you should make sure that the object's Dispose method gets called when you are finished using the object. You can do this with the C# using statement or by implementing a try/finally block in other languages that target the common language runtime.

The C# programming language's using statement makes a call to the Dispose method more automatic, by simplifying the code that you must write to create and clean up an object. The using statement obtains one or more resources, executes the statements that you specify, and then disposes of the object. Note that the using statement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. The following code example creates and cleans up an instance of the ResourceWrapper class, as illustrated in the C# example of implementing a Dispose method.

class myApp
{
   public static void Main()
   {
      using (ResourceWrapper r1 = new ResourceWrapper())
      {
         // Do something with the object.
         r1.DoSomething();
      }
   }
}

The preceding code, incorporating the using statement, is equivalent to the following.

class myApp
{
   public static void Main()
   {
      ResourceWrapper r1 = new ResourceWrapper();
      try
      {
         // Do something with the object.
         r1.DoSomething();
      }
      finally
      {
         // Check for a null resource.
         if (r1 != null)
         // Call the object's Dispose method.
         r1.Dispose();
      }
   }
}

The C# using statement allows you to acquire multiple resources in a single statement, which is equivalent internally to nested using statements. For more information and a code example, see using Statement (C# Reference).

When you write managed code that uses an object that encapsulates a resource in languages other than C#, use a try/finally block to ensure that a call is made to the object's Dispose method. The following code example creates and cleans up an instance of the Resource class, as illustrated in the Visual Basic example of implementing a Dispose method.

class myApp
   Public Shared Sub Main()
      Resource r1 = new Resource()
      Try
         ' Do something with the object.
         r1.DoSomething()
      Finally
         ' Check for a null resource.
         If Not (r1 is Nothing) Then
            ' Call the object's Dispose method.
            r1.Dispose()
         End If
      End Try
   End Sub
End Class
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.