C#
  Home arrow C# arrow Page 3 - C# Tips: Keep it Short, Get it Done
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

C# Tips: Keep it Short, Get it Done
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 24
    2006-01-30

    Table of Contents:
  • C# Tips: Keep it Short, Get it Done
  • Implementing IDisposable
  • Using “using”
  • Using “as” and “is"

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    C# Tips: Keep it Short, Get it Done - Using “using”


    (Page 3 of 4 )

    The “using” statement is one of the best ways to see to it that resources are properly disposed of. This construct effectively provides a “try/finally” statement in which the object referenced directly by the “using()” clause is explicitly disposed of in the finally block. The following two examples will produce basically the same IL and have the same effect.

    MyClass obj = null;
    try
    {
         obj = new MyClass();
         obj.DoSomething();
    }
    finally
    {
         if (null != obj)
              obj.Dispose();
    }

    using (MyClass obj = new MyClass())
    {
         obj.DoSomething();
    }

    In both cases, “obj” is local to the block in question, though it is clear that “using” requires writing less code and spares us the trouble of explicitly disposing of that object. Remember, even though the garbage collector should be able to rely on your object finalizers as a hook for the “Dispose()” method, you should still code defensively and be certain that objects are properly disposed of yourself whenever possible.

    The “using” statement can be nested just like “try” statements. For example, suppose you are trying to create a “DataReader” to bind to an ASP.NET grid. For the sake of brevity, non-relevant code is omitted.

    protected DataGrid MyGrid;

    private void Page_Load(object sender, System.EventArgs e)
    {
         using (SqlConnection dbCxn = new SqlConnection(“connection
    string”))
         {

              dbCxn.Open();

             string sql = “SELECT * FROM MyTable”; 
              using (SqlCommand dbCmd = new SqlCommand(dbCxn, sql))
              {

                  using (DataReader reader =                                                       dbCmd.ExecuteReader(CommandBehavior.CloseConnection))
                  {
                       MyGrid.DataSource = reader;
                       MyGrid.DataBind();
                  }
              }
         }
    }

    In this example, if we encounter failure at any point while connecting to the database, querying the database, or binding the data, the grid will simply not be databound. All of the objects will be properly disposed of when the “using” statement is exited. Exiting the statement happens when all the code inside the statement has run or when an exception is thrown.

    Can you see a potential problem with the “using” statement? What if you try to use an object that does not support the “IDisposable” interface? Well, you simply cannot do that. To use an object in a “using” statement, that object must implement “IDisposable.” I am referring to the object appearing in the actual “using ()” portion, not in the inner block code; you can do whatever you like there.

    Note that you do not have to define the object in the “using ()” block, but I recommend it. Unless for some reason you need to use the object outside the scope of the “using” statement, always declare and initialize the object within the “using ()” block itself.

    More C# Articles
    More By David Fells


       · Hello! Thanks for checking out my article. Your comments and feedback are welcome,...
       · One important tip: Don't overuse the "as" operator.For example, if myObject is...
     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT