I understand that using the as operator to cast an object, over an explicit cast, is usually more desirable due to the fact that if the cast fails, the reference variable goes to null instead of throwing an exception.
However, lets say I check to see the type of class an object is, that’s inside of a List, prior using the as operator, like so,
DrawableGameComponent drawComponent;
foreach (component in Components)
{
if (component is DrawableGameComponent)
{
drawComponent = component as DrawableGameComponent;
// do something with drawComponent
}
}
does using the as operator lose its benefits by checking with the is operator first? So doing the following cast is just as good, because we first check the class type using is before attempting the cast?
if (component is DrawableGameComponent)
{
((DrawableGameComponent)componet).Visible = true;
}
I’m just wondering if there is some underlying piece I’m missing, or if this truly comes down to a matter of taste which pattern to use. Does the latter pattern create garbage through the explicit cast?
Thanks in advance!
better (saves one “cast” – compare the generated IL):