Search code examples
c#wpfuser-interfaceeto

how to find a generic UI class in a list of different class without specifying the type?


enter image description here

I made a generic UI class called DraggableLayout. It's a treelike Layout that nest within other DraggableLayout

The thing is, I need the children to be able to search for the DraggableLayout when I am looping through the list of Controls in parents.

        foreach (var tab in Parents)
        {
            if (tab is DraggableLayout) //Error CS0305
            {
               //Do Something
            }
        }

When I do the above, I need to specifiy the type. Is it possible to ignore the and search for a parent generic class ?


Solution

  • What you can do is:

    var tabType = tab.GetType();
    if (tabType.IsGenericType
        && typeof(DraggableLayout<>)
            .IsAssignableFrom(tabType.GetGenericTypeDefinition()))
    { ... }
    

    Or with an extension method:

    public static bool IsOfGenericType(this Type source, Type genericType)
    {
        return source.IsGenericType
            && genericType.IsAssignableFrom(source.GetGenericTypeDefinition());
    }
    
    // ...
    if (typeof(tab).IsOfGenericType(typeof(DraggableLayout<>)))
    { ... }