Reputation: 37
This will seem a lot like another post I made but I am writing a similar program in C#.
I have class Card and class Land which is a subclass of Card. In Java, I used instanceof
to determine if it was a child of Card.
The object being referred to is held in the variable c
I have already tried:
if (typeof (Land).isSubClassOf(typeof(Card))){
//random code
}
What i'm trying to do, in java, would be:
if ( c instanceof Land){
}
Upvotes: 0
Views: 1891
Reputation: 29202
Don't check for the type and then cast. If you do that you're really checking the type twice. Do this:
var l = c as Land;
If c
can be cast as Land
then l
will contain that. If not it will be null
.
If you do this:
if(c is Land)
l = (Land)c;
Then you're actually inspecting c
twice. Once to check whether it is of type Land
, and then again to do the actual cast.
Upvotes: 1
Reputation: 30022
For direct inheritance :
static void Main(string[] args)
{
Land c = new Land();
bool isCard = c.GetType().IsSubclassOf(typeof(Card));
}
Or:
static void Main(string[] args)
{
Land c = new Land();
bool isCard = c is Card;
}
Upvotes: 3