Intriguing question. Actually, I use them all the time. is is handy to find out whether an object is of a certain type, I use that occasionally in generics or in loops through objects that are of different types. It is also invaluable with Reflection.
The other, as finds many more uses. It is often much safer to use then a normal cast: when it fails, it returns null, instead of an exception. I also find it clearer syntax and easier to use it, check the return value for null, then to add an exception block.
Basically, what I mean to say is, I prefer this:
protected void GeneralEventHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
if(btn != null) // click came from a button!
// do something
else
// other cases
}
and this:
protected void GeneralEventHandler(object sender, EventArgs e)
{
if(sender is Button) // click came from a button!
// do something
else
// other cases
}
as opposed to this:
protected void GeneralEventHandler(object sender, EventArgs e)
{
try
{
Button btn = (Button) sender;
// if we get this far, it's a button
}
catch(InvalidCastException ice)
{
// click did not come from a button! Handle other cases
}
}
of course, this is just an example, but when I can avoid try / catch, I will. This also lets more room for real exceptions to get through.
answered 2009-10-15T13:09:58.013