Sossenbinder
Sossenbinder

Reputation: 5282

Why can't I add a Form label to my Label list?

I got this code right here and it's not really working the way it should :

private void Form1_Load(object sender, EventArgs e)
{
    weather = new Weather();
    dynamic weatherObject = weather.refreshData();
    gui = new GUICreator(weatherObject);

    List<Label> labelList = new List<Label>();

    foreach(Control element in this.Controls)
    {
        if (element.GetType() == typeof(Label))
        {
            labelList.Add(element);
        }
    }
}

The problem is mostly the loop which is supposed to populate the list with all available labels in my form in order to make it ready to be passed to some other class.

However, I always get an error at the labelList.Add(element) line, which is: "The best overloaded method match for System.Collections.Generic .... has some invalid arguments".

I don't get whats going wrong here. I double checked if the element is the right type at that certain line, and it indeed always is a Label. What's wrong? I can't remember having to add another thing to a List.add except for the element which is to be added?

Upvotes: 1

Views: 171

Answers (3)

Steve
Steve

Reputation: 216263

The problem is the fact that the compiler sees a Control object added to a List<Label>. The compiler cannot look at your code and understand from your logic that you are adding only Labels. Instead if you write

 foreach(var element in this.Controls.OfType<Label>())
 {
     labelList.Add(element);
 }

now you are giving enough info to the compiler and it can understand that you are adding Labels and not generic Controls

And, as noted below from ASh, if your intent is just to have a List<Label> without further processing then you could just write a single line

  List<Label> labelList = this.Controls.OfType<Label>().ToList();

Upvotes: 2

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

This is the code behind the List<T>.Add method:

public class List<T>
{
    public void Add(T item)
    {
        if (this._size == this._items.Length)
        {
            this.EnsureCapacity(this._size + 1);
        }
        this._items[this._size++] = item;
        this._version++;
    }
}

As you can see, it is only accepts parameters which are of the type T, which you have set when you initialized the list.

   List<Label> labelList = new List<Label>();

Now when looping through the elements you specify that the items to iterate over are of the type Control. In the List, T is not Control, as its of the type Label.

You should cast the Control variable (item) to Label, as Label extends from Control.

Upvotes: 1

Btc Sources
Btc Sources

Reputation: 2041

You've to cast element to Label, to match the List type.

labelList.Add((Label) element);

Upvotes: 0

Related Questions