AustinWBryan
AustinWBryan

Reputation: 3326

How to find the tag of a generic control in C#

I'm creating a function that allows you to search for a control by the tag. The only parameter is the name of the tag. It returns a list of all the type T controls with the tag. This is what I have:

public static List<T> FindWithTag<T>(string tag)
{
    List<T> types = new List<T>();

    foreach (T type in fm.Controls.OfType<T>())
        if (type.Tag == tag)
            types.Add(type);
    return types;
}

Problem is, since T is a generic variable, it doesn't have a tag property. I can understand why, because could be an int or a string. How can I tell the compiler that T is only for controls, and would therefore have a tag?

Thanks in advance.

Upvotes: 0

Views: 624

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can specify the type which should your T type be inherited from.

public static T[] FindWithTag<T>(string tag) where T : Control
{
    List<T> types = new List<T>();

    foreach (T type in fm.Controls.OfType<T>())
        if (type.Tag == tag)
            types.Add(type);
    return types;
}

By the way, calling a foreach local variable type confused me because actually you are enumerating through controls. So, it should be

 foreach (T control in fm.Controls.OfType<T>())

It also applies to List<T> types which is, by fact, a list of Control. Sometimes, incorrect name of a single variable can make code much less readable :)

Upvotes: 5

Related Questions