Pro C# 2010 and the .NET 4 Platform
By: Andrew Troelsen
Publisher: Apress
Pub. Date: May 14, 2010
Print ISBN: 978-1-4302-2549-2
Web ISBN: 1-4302-2549-1
Pages in Print Edition: 1752
-----------------------------------------------------------------------------------------
Until very recently, I continued to cast my variables in the old-school C/C++ fashion. That form of type casting required the following syntax:
Vehicle objCurrentVehicle = (Vehicle)objTractorTrailer;
One problem with the above logic is that an Exception will be thrown if objTractorTrailer is null. Defensive coding would dictate that we first make sure that objTractorTailer is not null and that it is an object that derives from the Vehicle base class.
"As" to the rescue!
Vehicle objCurrentVehicle = objTractorTrailer As Vehicle
if (objTractorTrailer != null)
Here, .Net will ensure that objCurrentVehicle is null if, for any reason, objTractorTrailer cannot be cast as a Vehicle.
What about "Is"?
If all you need to know is whether a particular variable is compatible with a data type, then "Is" will help.
if (objTractorTrailer Is Vehicle)
Do not use the "Is" condition as a predecessor to performing an "As". If you do that, then your code will, in fact, attempt to cast the variable twice. If you know you will be performing an "As" operation, then simply do that and check for null. If you are merely performing the operation just to make a decision, then simply use the "Is" operator.
CD
No comments:
Post a Comment