comphunter159
comphunter159

Reputation: 37

c# test if a class is a subtype of another class

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

Answers (3)

Scott Hannen
Scott Hannen

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.

C# As keyword

Upvotes: 1

Zein Makki
Zein Makki

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

Rahul Hendawe
Rahul Hendawe

Reputation: 912

if(foo is Bar) {
    return (Bar)foo;
}

Upvotes: 3

Related Questions