Type checking by InvalidCastException:
Common uses:
- Checking the type of an object in a collection when the developer does not know about the "is" operator or its equivalents.
Selection selItems = UtilServices.GetInstance().GetSelectedItems();
if (selItems != null)
{
try
{
foreach (object item in selItems)
{
// Cast to a Foo Item.
FooItem fooItem = (FooItem)item;
}
ProcessSuccess();
}
catch (System.Exception ex)
{
// If an exception is thrown, the items are not FooItems
Logger.Error("Exception: " + ex.Message);
ProcessFailure();
}
}
Null checking by Exception handler:
Common uses:
- Not being bothered by the hassle of all those "if" statements.
try
{
foo = bar.GetSomeData();
thing = foo.ThingValue;
}
catch
{
foo = bar.GetOtherData();
thing = foo.ThingValue;
}