0

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


        }
1
  • 2
    This is almost always the wrong thing to be doing. If you're going to have a collection of parent objects, the parent type should have whatever members you need to use for every object in this collection. You should rely on polymorphism such that each item acts appropriately without you needing to know what its type is. Commented Apr 15, 2014 at 15:02

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

is it possible that in GameScreens type of array GamePlayScreen type coud exist, i am unable to understand your logic, please if you explain it for me
but your answer is great learned a new thing..hope i remember it i my mind..:)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.