Pages

Wednesday, 22 July 2015

using Statement

using Statement

Certain types of unmanaged objects are limited in number or are expensive with system resources. It’s important that when your code is done with them, they be released as soon as possible. The using statement helps simplify the process and ensures that these resources are properly disposed of. A resource is a class or struct that implements the System.IDisposable interface. The IDisposable interface contains a single method, named Dispose.

The phases of using a resource are consist of allocating,using and disposing the resource. If an unexpected runtime error occurs during the portion of the code using the resource, the code disposing of the resource might not get executed.

Packaging the Use of a Resource

The using statement helps reduce the potential problem of an unexpected runtime error by neatly packaging the use of a resource.

There are two forms of the using statement. The first form is:
using ( [Resource Type] [Identifier] = [Expression] ) 
{
 [Statements]
}

  • The code between the parentheses allocates the resource.
  • Statement is the code that uses the resource.
  • The using statement implicitly generates the code to dispose of the resource.

For example:
 static void Main()
 {
  using (TextWriter tw1 = File.CreateText("Lincoln.txt"),
   tw2 = File.CreateText("Franklin.txt"))    //handle multiple resources
  {
   tw1.WriteLine("Four score and seven years ago, ...");
   tw2.WriteLine("Early to bed; Early to rise ...");
  }
  
  using (TextReader tr1 = File.OpenText("Lincoln.txt"),
      tr2 = File.OpenText("Franklin.txt"))    //handle multiple resources
  {
   string InputString;
   while (null != (InputString = tr1.ReadLine()))
   Console.WriteLine(InputString);
   while (null != (InputString = tr2.ReadLine()))
   Console.WriteLine(InputString);
  }
 }

Another form of the using statement is the following:
using ( [Expression ]) {
Statement
}

In this form, the resource is declared before the using statement.
 static void Main()
 {
 TextWriter tw1 = File.CreateText("Lincoln.txt")
 using (tw1)
 {
  tw1.WriteLine("Four score and seven years ago, ...");
 }
 TextReader tr1 = File.OpenText("Lincoln.txt");
 using (tr1)
 {
  string InputString;
  while (null != (InputString = tr1.ReadLine()))
   Console.WriteLine(InputString);
 }
 }

Although this form still ensures that the Dispose method will always be called after you finish using the resource, it does not protect you from attempting to use the resource after the using statement has released its unmanaged resources, leaving it in an inconsistent state. It therefore gives less protection and is discouraged.

0 comments:

Post a Comment