0

I wanted to check the class type regardless inheritance tree, amongst the children of Canvas. so I made a reusable function like below.

private int FindIndexOf(Type _t)
    {
        if (wrappingGrid == null)
            return -1;

        for(int i =0; i< wrappingGrid.Children.Count; ++i)
        {
            if(wrappingGrid.Children[i].GetType() == _t)
            {
                return i;
            }
        }
        return -1;
    }

But it works with only type-strict.

wrappingGrid.Children[i] is _t

This doesn't work either because the 'Type' type is not what I want to compare with. and it causes a syntax error. Probably I need to make a template function. But I'd better write simpler code.

I've already looked into other articles as well. Type Checking: typeof, GetType, or is?

Do you have any idea? Thank you in advance..

Mark Choi
  • 420
  • 6
  • 16

1 Answers1

5

Maybe you should try wrappingGrid.Children[i].GetType().IsSubClassOf(_t)

EDIT @usr: Yes: IsAssignableFrom is better, but then it has to be called vice versa:

_t.IsAssignableFrom(wrappingGrid.Children[i].GetType()

Fratyx
  • 5,717
  • 1
  • 12
  • 22
  • I think IsSubClassOf says false for equal types. You have to use IsAssignableFrom. – usr Jan 26 '18 at 12:34