Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for type in loop?

Tags:

c#

I know how to check a type of a field directly. But how could I implement something like this

    private bool checkJumpObstacle(Type type)
    {
        foreach (GameObject3D go in GameItems)
        {
            if (go is type) // won't accept 'type'
            {
                return true;
            }
        }
        return false;
    }

For type, I'd like to pass Car, House or Human as a parameter (those are all classes). But this kind of code doesn't work.

like image 710
Luzius L Avatar asked Dec 05 '22 11:12

Luzius L


1 Answers

EDIT: It's actually even easier using Type.IsInstanceOfType if you can't make it a generic method:

private bool CheckJumpObstacle(Type type)
{
    return GameItems.Any(x =>type.IsInstanceOfType(x));
}

It sounds like you probably want Type.IsAssignableFrom

if (go != null && type.IsAssignableFrom(go.GetType());

Note that this is assuming you want inherited types to match.

Also, if at all possible, use generics instead. Aside from anything else, that would make the method really simple:

private bool CheckJumpObstacle<T>()
{
    return GameItems.OfType<T>().Any();
}

Even without that, you can still use LINQ to make it easier:

private bool CheckJumpObstacle(Type type)
{
    return GameItems.Any(x => x != null && type.IsAssignableFrom(x.GetType()));
}

Obviously if you don't expect any null values, you can get rid of the nullity check.

like image 158
Jon Skeet Avatar answered Dec 20 '22 11:12

Jon Skeet