Vallabh Patade
Vallabh Patade

Reputation: 5110

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?

Upvotes: 0

Views: 261

Answers (4)

VidasV
VidasV

Reputation: 4895

var item = obj.GetItem(i);
if(item is B) {
   B b = (B) item;
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499900

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.

Upvotes: 5

Daniel
Daniel

Reputation: 9040

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());
}

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

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.

Upvotes: 1

Related Questions