C#
  Home arrow C# arrow Page 4 - 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 “as” and “is"


    (Page 4 of 4 )

    The “as” operator provides a semantically logical and programmatically safe type cast. One of the more common situations requiring explicit casts is when working with ASP.NET web controls and navigating the control hierarchy. In the following example, we need to convert a web control’s “Parent” reference to its proper type, in this case a “DataGridItem.”

    Using C-style casts:

    try
    {
         DataGridItem d = (DataGridItem)obj.Parent;
         if (d.GetType() == “DataGridItem”)
         {
              // Do something with d
         }
    }
    catch (InvalidCastException e)
    {
         …
    }

    Using “as”

           

    DataGridItem d = obj.Parent as DataGridItem;

    if (null != d)
    {
         // Do something with d
    }

    Always use “as” in place of the traditional C-style cast. Do not use “as” in place of casting methods exposed by the object itself unless you are certain of the result. For example, you should not use “object as string” when you could use “object.ToString()” because it is assumed that the object knows better how to cast itself than the runtime.

    The “is” operator is a native language construct that exposes an object’s type. “is” spares one method call in IL by avoiding the call to “Object.GetType()”. If you are familiar with Visual Basic, you will recognize this operator.

    Using the example for the “as” operator, consider this statement:

    DataGridItem d = obj.Parent as DataGridItem;

    if (d is DataGridItem)
    {
         // Do something with d
    }

    The difference, as you probably noticed, is that in the “as” example d is compared for inequality against null, whereas in the “is” example it was compared against the type in question. Using “is” is more intuitive, more readable, and slightly more efficient, making it by far the better choice.

    Using “is” and “as” result in fewer lines of IL and fewer lines of actual C# code by avoiding a lot of extraneous checks and statements, which is evident from the examples above.

    Conclusion

    There are always plenty of other ways to improve your code and I encourage you to pursue them. The contents of this article, while useful, are only a piece of the puzzle. In this article we looked at a couple of basic ways to clean up your C# code. First we reviewed object disposal and the “IDisposable” interface and how it can be used to clean up unmanaged resources. Second, we talked about the “using” statement, which guarantees proper object disposal. Then we talked about the “is” and “as” operators. “as” provides a safe type cast and “is” provides a safe type check.

    The .NET framework provides solid garbage collection and IL optimization, but remember to help out when you can by making sure unmanaged resources are handled and that your objects are disposed of properly. In a managed environment you only have to worry about disposing of types that contain unmanaged resources, or types that are derived from types that implement the “IDisposable” interface. Also be sure to choose operators and statements that allow you to write fewer lines of code and write code that is more readable and more intuitive. Always keep these things in mind when coding in C#.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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