Employing the using Statement


As explained in Chapter 19, the using statement can be used to automatically release an object, rather than calling Dispose( ) explicitly. Recall that it has these general forms:

 using (obj) {   // use obj } using (type obj = initializer) {   // use obj }

Here, obj is an object that is being used inside the using block. In the first form, the object is declared outside the using statement. In the second form, the object is declared within the using statement. When the block concludes, the Dispose( ) method is automatically called. The using statement applies only to objects that implement the System.IDisposable interface (which, of course, all components do).

Here is a client for CipherComp that employs using rather than calling Dispose( ) directly:

 // Employ the using statement. using System; using CipherLib; // import CipherComp's namespace class CipherCompClient {   public static void Main() {     // cc will be disposed when this block ends.     using(CipherComp cc = new CipherComp()) {       string text = "The using statement.";       string ciphertext = cc.Encode(text);       Console.WriteLine(ciphertext);       string plaintext = cc.Decode(ciphertext);       Console.WriteLine(plaintext);     }   } }

The output from the program is shown here:

 Uif!vtjoh!tubufnfou/ The using statement. Dispose(True) for component 0 Closing file for component 0

As the output shows, Dispose( ) was called automatically when the using block ended. Whether you use using or explicitly call Dispose( ) is up to you, but using does streamline your code.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net