Pectus Excavatum
Pectus Excavatum

Reputation: 3773

c# how to check if an object is of a certain type

I am just wondering what the process is for checking the object type of something.

Basically I have an array of parent objects and I want to check if one of those objects is of a particular child type.

more specifically, I want to check if an array of GameScreen objects contains a GameScreen object of type GameplayScreen.

        GameScreen[] screens = mScreenManager.GetScreens();

        // loop through array and check if the object equals gameplayscreen


        }

Upvotes: 0

Views: 1588

Answers (2)

joppiesaus
joppiesaus

Reputation: 5750

Use the is keyword when you want to check a type.

class Foo {}
class SuperFoo : Foo {}

bool IsSuperFoo(Foo foo)
{
    if (Foo is SuperFoo) return true;
    return false;
}

You can do the same for your GamePlayScreen.

Upvotes: 1

Habib
Habib

Reputation: 223207

You can check the type using is operator like:

if(screens[0] is GamePlayScreen)

Or if you just need GamePlayScreen type objects from your array you can use :

GamePlayScreen[] items = screens.OfType<GamePlayScreen>().ToArray();

See: Enumerable.OfType. It uses System.Linq

Upvotes: 5

Related Questions