.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

  • On-demand Event Event Date: May 18, 2015 While the idea of using facial and/or gesture recognition to create a modern, intuitive game seems attractive, some developers may want to leverage Unity 3D as a way to accelerate their development efforts. There are many different ways in which Intel and Unity Technologies have been working together to help speed the development of games with the Intel&reag; RealSense™ SDK (software developer kit). Check out this webcast to join a panel of experts as they …

  • On-Demand eSeminar DevOps and Cloud are all the rage in IT, but the two terms relating process and computing aren't mutually exclusive. Join us to see how your movement into cloud changes the way you develop, deploy, test and manage, and how DevOps can actually be a good thing when coupled with cloud.

Most Popular Programming Stories

More for Developers

RSS Feeds

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