Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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<>)))
{ ... }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading