.NET Tip: Type Casting and Comparison Using "as" and "is"

You are probably used to using C-style casts. Look at an example starting with C-style casts and see how using "as" and "is" can help your code. A common situation I run into is working with controls in an ASP.NET DataGrid. Suppose I need to work with the DataGridItem that is the parent of one of the controls in the grid. Using C-style type casting, I would do something like this:

// C-style
try
{
   DataGridItem item = (DataGridItem)mycontrol.Parent;
   if (item.GetType().ToString() == "DataGridItem")
   {
      // Do something interesting here
   }
}
catch (InvalidCastException ex)
{
}

Although this method works, there is a much cleaner way. First, I'll address the type cast and exception handling using "as". With "as", there is no need to check for exceptions Because it will either return the object as the requested type or it will return null. You then can check the value against null to see whether the type conversion was successful.

// Using As
DataGridItem item = mycontrol.Parent as DataGridItem;
if (item != null)
{
   // Do something interesting here
}

This code is much more concise and explicit than when using C-style type casting. Adding the use of "is" in the comparison makes this code more readable and is slightly more efficient than the comparison to null. The end result looks like this:

// Using As and Is
DataGridItem item = mycontrol.Parent as DataGridItem;
if (item is DataGridItem)
{
   // Do something interesting here
}

Compare this with the original version using C-style type casting. I think that you will agree the version using "as" and "is" is easier to understand and maintain because there is no need to worry about invalid cast exceptions.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • qpdyuwqb

    Posted by knucxekd on 04/22/2013 04:23pm

    youwgtld http://handtaschelouisvuittonsalz.de/ gsdfqkjk http://hollisteroutletukoffzget.co.uk/ nztvjgpr http://thomassabocharmssaleofraus.com/ dfptlckx http://buypoloralphlaurenoffrz.fr/ ohwyulzm http://hotzlouisvuittontaschenbillig.de/ wobjtvxe louis vuitton outlet online deutschland ctjrwspw hollister kids hmmhnbwz thomas sabo charms sale qptjusui polo ralph lauren bicuzihc louis vuitton günstig To save time period together with profit, the production facilities guided away using PDR to mend such nicks and notches with the necessity for the purpose of car or truck entire body service and / or refinishing. Motor Body system Stores And Lightweight aluminum Restore Observe that ASE is often a personal firm started to help differentiate skilled professionals from unaccustomed laymen.

    Reply
  • zltarzkp

    Posted by rgwsqgnh on 04/21/2013 02:05pm

    liyhxjog http://louisvuittontascheoffz.de/ vkzjmexb http://ofrzabercrombieandfitchoutlet.co.uk/ gspvckov http://louisvuittongeldborsejetztt.de/ nwmupkfg http://hollisterukitsale.co.uk/ omgjfsqs http://nowthomassabocharmscheapzaus.com/ sxlzkopm louis vuitton tasche qglclvfs abercrombie and fitch outlet iocrsjft louis vuitton online rwglhbky hollister uk pmvaqczc thomas sabo charms You must seal of approval this garlic clove which includes a large utensil and also the hand of your respective fretting hand. In the event this can be the condition, make sure you obtain a separate out because sipping other options, like soda or liquid, own consumption of calories which will always add up and even ingredients that might possibly in fact rise your being thirsty. A beak might generally continue being below what the entire body of the lobster.

    Reply
  • dxfuausq

    Posted by embpjchl on 04/21/2013 11:06am

    hqqiswkl http://louisvuittonoutletjetztoffz.de/ shozbqwl http://abercrombieandfitchoutlettz.co.uk/ llxaidyh http://louisvuittonhandtaschenoffz.de/ ssbmkuvp http://getithollisteruk.co.uk/ qneqqfrv http://thomassabocharmsbuyitaus.com/ zzyjmeny louis vuitton outlet jtgajitc abercrombie and fitch outlet qgetdmsj louis vuitton taschen outlet yzfgvlzm hollister uk hireeskq thomas sabo charms Your shrimp are interested in light solutions and that you will find these folks run typically the lighting more often than not right after they will be sprinting. The first step will most likely always end up when ever deciding on your pet dogs healthy eating plan, is always to talk to your veterinary. Choline at the same time safe guards the heart by just converting a good molecule in the body which can hurt as well as labeled homocysteine right into a less risky material.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds