Casting in C# – the ‘as’ and ‘is’ operators (Part I)

There are different ways to cast one type to another in C#. Lets try compile-time first,

cast5.JPG

This gives us an error at compile-time, so we know we need an explicit cast. Lets try the old C style,

cast1.JPG
This causes a CLR type safety check (CLR checks if ‘obj’ is cast-able) and an invalid cast exception is thrown if ‘obj’ is not cast-able to ‘XmlDocument’. Lets check if it can be cast ourselves,

cast2.JPG

This way, even though there are two type checks, we gain by not having to worry about an exception being thrown if the cast fails – we know it won’t fail.
C# has introduced two new keywords that make casting simpler. The ‘is’ keyword pretty much does what we did in the example above (see this for an important difference), it checks if ‘obj’ is cast-able to XmlDocument,

cast3.JPG
The snippet above actually causes two CLR type safety checks. This can be optimized by using the ‘as’ keyword.

cast4.JPG

The ‘as’ keyword is guaranteed to never throw an InvalidCastException. If the cast is unsuccessful the result is null. This way only one type check is required to cast and also we don’t need to worry about exceptions being thrown.

Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Casting in C# – the ‘as’ and ‘is’ operators (Part I)

  1. Siegfried says:

    Thx for your article. Is there an alternate compile time check except for assign to a reference
    “is” “as” and “cast” operator are all runtime type checks
    I would like to have an operation rather than a statement for compile time check.
    Have you any idea?
    It seems implicit conversions are compile time checked but can’t be explicitly called. This leaves me no option than to write all compile time casts in 2 lines
    B b = a;
    b.DoSomething();
    can not fail at runtime but:
    ((B)a).DoSomething();
    can fail at runtime 😦

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

%d bloggers like this: