Reputation: 7490
I just came across the code below:
public void ListControls(ControlCollection controls, List<Control> controlsFound)
{
foreach (var control in controls)
{
if (control is IAttributeAccessor)
{
controlsFound.Add(control); //Error (Invalid argument to Add method)
ListControls(control.Controls, controlsFound);
}
}
}
It gives an error as above:
If I change var
in foreach
to Control
then it works. The reason is that the Add
method was expecting Control
as parameter. But I think var should have been implicitly replaced by Control
, right?
Upvotes: 0
Views: 78
Reputation: 1038
Using LINQ will work:
public void ListControls(ControlCollection controls, List<Control> controlsFound)
{
foreach (var control in controls.OfType<Control>())
{
if (control is IAttributeAccessor)
{
controlsFound.Add(control); //Error (Invalid argument to Add method)
ListControls(control.Controls, controlsFound);
}
}
}
Upvotes: 1
Reputation: 136174
No, it doesnt because ControlCollection only implements the non-generic IEnumerable
not the generic IEnumerable<Control>
so when you enumerate it without providing the type, you get object
Upvotes: 4