NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

So someone e-mailed to ask me why I used as to cast my object:

IHiThere asm = o as IHiThere;
if (asm != null)
{
   MessageBox.Show(asm.Hi());
}
else
{
   MessageBox.Show("Failed to make asm = o");
}

Rather than:

IHiThere asm = (IHiThere)o;

When it is neater.

Well, there is a simple reason: This is because the as operator doesn't throw an exception when it fails but instead fills the variable with null. The check if the value was null checked if the code worked or not.

Note that in the real world you will want exception handling around the whole block, incase the user selects the wrong type of dll, or access to it is denied, or... well, you get the picture.  This means you can freely use brackets to cast it - but this is in my opinion a more elegant method of doing something where you want to know if it succeeded or failed.

Update in 2009:

I would just like to clarify that I was trying to make the point that you should use the as keyword when it's something you expect not to work but don't want to use the is keyword!

Permalink