.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

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

  • U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there's simply not enough quality talent to go around. In response, companies often resort to inferior solutions -- hiring substandard developers and engineers, recruiting talent on a part-time or temporary basis, poaching people from competitors, or burdening an already stressed IT staff for more of their labor. Fortunately, there's a better solution. Read this white paper to learn the business value of …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date