Cast objects may be usual in our applications but how can we defend our code from invalid cast exceptions?
For reference types we can use the operators is and as.
The operator is performs a check and retrieves a Boolean value that indicates if the object has the same type than the object specified in the condition statement as following:
public class Foo
public class Bar : Foo
Foo foo = new Foo();
if (foo is Foo)
Console.WriteLine(“foo is Foo”);
Console.WriteLine(“foo is not Foo”);
if (foo is Bar)
Console.WriteLine(“foo is Bar”);
Console.WriteLine(“foo is not Bar”);
The operator as performs a cast and retrieves a valid object when the cast is possible or a null value when the cast is invalid. An InvalidCastException is not thrown.
void MyMethod(object o)
Foo foo = o as Foo;
if (foo != null)
// Valid cast
// Invalid cast
Keep in mind that if there is a way to check for exceptions in your code, you should do it and do not forget that there is more in .NET than only try/catch blocks for exception handling.