0

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 ?

1 Answers1

0

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<>)))
{ ... }
Xerillio
  • 4,855
  • 1
  • 17
  • 28
  • it worked like a charm! Thanks! what do you mean by: "I see my suggested duplicate was not quite the same."? –  Sep 05 '22 at 19:39
  • @Wiley Nevemind :) I thought I had found a duplicated question I linked in a comment to your question at first, but I guess you didn't see it before I deleted it. – Xerillio Sep 05 '22 at 19:48