Reputation: 5110
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
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
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
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
returnsnull
instead of raising an exception.
Upvotes: 1