Sander Koldenhof
Sander Koldenhof

Reputation: 1313

Check if object is child of a class

I want to know if a certain object is of a certain Type that is a child class. I've got 3 classes: Participant, Human : Participant and AI : Participant where the instances are implemented as followed:

Participant player1 = new Human();

Participant player2 = new AI();

I've got these players in an participants[2]{ player1, player2 }; and a variable currentParticipant that keeps track of who's turn it is.

I want to check if participants[currentParticipant] is of type AI, which I have done like this:

private void CheckParticipantsTurn(int currentParticipant)
    {
        if(participants[currentParticipant] is AI)
        {
            participants[currentParticipant].AiMove(); //currently empty
            MessageBox.Show("Ai moved");
        }
        ChangeCurrentParticipant(currentParticipant); //switches current participant
    }

However, it never seems to see player2 as an AI - it sees it as a Participant.

Question:

How do I check if player2 is of type AI, instead of Participant?

Upvotes: 0

Views: 2028

Answers (1)

Hitesh P
Hitesh P

Reputation: 416

You can check if ( participants[currentParticipant].GetType() == typeof(AI) )

Upvotes: 1

Related Questions