Typecasting an object in C#

Assume I have a method which returns object of class A

A getItem(int index)

Now I have following line of code, (I assume B is subclass of A)

B b = (B) obj.getItem(i);

but before this I have to make sure that I can typecast it into B as getItem can return object of some other subclass, say C, of A

Something like this

    if(I can typecast obj.getItem(i) to B) {
             B b = (B) obj.getItem(i);
    }

How I can do this?

Jon Skeet
people
quotationmark

Two options:

object item = obj.getItem(i); // TODO: Fix method naming...
// Note: redundancy of check/cast
if (item is B)
{
    B b = (B) item;
    // Use b
}

Or:

object item = obj.getItem(i); // TODO: Fix method naming...
B b = item as B;
if (item != null)
{
    // Use b
}

See "Casting vs using the 'as' keyword in the CLR" for a more detailed comparison between the two.

people

See more on this question at Stackoverflow