Monday, 7 December 2009

is, then as (C#)

The C# language has a pair of related operators, is and as. Say you have an object, x, and you want to know if its really type Form underneath.

(x is Form) will be true if it is, or false if it isn't. The as operator will actually perform the conversion, returning null if it can't be converted to that type.

One common piece of advice to C# programmers is to avoid using the is operator. Here's how both of these operators are typically used together.
    if (x is Form)
        Form frm = x as Form;
        /* Use frm. */

While the code works, all the is operator is doing is performing an as operation, and checking if the result is null or not. In other words, (x is Form) is equivalent to (x as Form != null). This means the code above is really saying...