0

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?

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
  • Here is a useful link: :) http://stackoverflow.com/questions/7042314/can-i-check-if-a-variable-can-be-cast-to-a-specified-type – NicoRiff Jul 20 '15 at 19:16

4 Answers4

5

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2
var item = obj.GetItem(i);
if(item is B) {
   B b = (B) item;
}
VidasV
  • 4,335
  • 1
  • 28
  • 50
1

Use as instead:

B b = obj.getItem(i) as B;
if(b != null)
    // cast worked

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

Try the as keyword. See https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

Base b = d as Base;
if (b != null)
{
   Console.WriteLine(b.ToString());
}
Daniel
  • 8,794
  • 4
  • 48
  • 71