Posted by: Cirilo Meggiolaro | 11/16/2008

Tip of the day #33 – Safely casts for reference type objects

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.

Operator is

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”);
else
    Console.WriteLine(“foo is not Foo”);

if (foo is Bar)
    Console.WriteLine(“foo is Bar”);
else
    Console.WriteLine(“foo is not Bar”);

Operator as

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
    }
    else
    {
         // 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: