Meeting the needs of your business from a distance

Interesting use of using clause mixed in a generic type

by Mark Shiffer 10/24/2008 2:43:00 PM

I am currently reading "More Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner and came across an interesting piece of syntax that I have not seen before. Below is an excerpt from the book.

Notice how the cast is used in the using statement. The neat thing here is that even if T doesn't support IDisposable, the code will still work, but if it does the object gets properly disposed off. That's nice!

[Begin Excerpt]

public void GetThingsDone()
{
    T driver = new T();
    using (driver as IDisposable)
    {
        driver.DoWork();
    }
}

This may look a bit confusing if you've never seen that sort of cast in a using statement, but it works. The compiler creates a hidden local variable that stores a reference to the driver cast as an IDisposable. If T does not implement IDisposable, then the value of this local variable is null. In those cases, the compiler does not call Dispose(), because it checks against null before doing this extra work. However, in all cases where T implements IDisposable, the compiler generates a call to the Dispose() method upon exiting the using block.

[End Excerpt]

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Research | Programming

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag





Live preview

January 6. 2009 17:17

About the author

Name of author Mark Shiffer
CEO & CIO of MS Consulting

E-mail me Send mail

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2009

    Sign in

    Copyright © 2001-2009 MS Consulting, Inc. All Rights Reserved.