It won’t blow up… but that doesn’t necessarily mean it’s safe.
Typically when I use a cast for a reference conversion, it’s because I really, really think that the execution-time type is the one I’m specifying. If it’s not, that indicates a bug in my code – and I’d rather that manifested itself as an exception.
If you’ve got bad data in your system, then continuing as if everything was fine is the dangerous path, not the safe path. That’s the way that as
will take you, whereas a cast would throw an InvalidCastException
, aborting whatever you’re doing before you get the chance to cause mayhem with the bad data.
as
is good if it’s valid for the object not to be of the given type – if it doesn’t indicate a bug. You almost always see the pattern of:
Foo x = y as Foo;
if (x != null)
{
...
}
See MSDN for more details about what as
does.
Note also that you probably don’t want to use ref
in your method. See my article on parameter passing for more details. Most of the time if I see people using ref
a lot, it’s because they don’t understand what it really means 🙂