Home > C# > Using Statement

Using Statement


Defines a scope, outside of which an object or objects will be disposed.

using (Font font1 = new Font(“Arial”, 10.0f))
{
}

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement theIDisposable interface. This interface provides the Dispose method, which should release the object’s resources.

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

using System;

class C : IDisposable
{
     public void UseLimitedResource()
     {
         Console.WriteLine(“Using limited resource…”);
     }

     void IDisposable.Dispose()
     {
         Console.WriteLine(“Disposing limited resource.”);
     }
}

class Program
{
    static void Main()
    {
      using (C c = new C())
      {
        c.UseLimitedResource();
      }
      Console.WriteLine(“Now outside using statement.”);
      Console.ReadLine();
    }
}

Output:
Using limited resource…
Disposing limited resource.
Now outside using statement.

 

Difference Between Finalize and Dispose Method

.NET Framework provides two methods Finalize and Dispose for releasing unmanaged resources like files, database connections, COM etc. This article helps you to understand the difference between Finalize and Dispose method.

Finalize vs dispose method

 

Implementing Finalize method (with dispose())

 

If you want to implement Finalize method, it is recommended to use Finalize and Dispose method together as shown below:

// Using Dispose and Finalize method together

public class MyClass : IDisposable

{

       private bool disposed = false;

       //Implement IDisposable.

       public void Dispose()

      {

            Dispose(true);

            GC.SuppressFinalize(this);

       }

       protected virtual void Dispose(bool disposing)

       {

              if (!disposed)

              {

                     if (disposing)

                    {

                           // TO DO: clean up managed objects

                   }

                   // TO DO: clean up unmanaged objects

                  disposed = true;

               }

       }

       //At runtime C# destructor is automatically Converted to Finalize method

      ~MyClass()

       {

             Dispose(false);

        }

}

Note

  1. It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary.
  2. At runtime C#, C++ destructors are automatically Converted to Finalize method. But in VB.NET you need to override Finalize method, since it does not support destructor.
  3. You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.
  4. A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has destructor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object’s Finalize method.
Advertisements
Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.

Thanks for your comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: