Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ListItem must be declared explicitly in foreach C#

Tags:

c#

asp.net

I'm confused as to why this code would not compile if listControl is a ListControl object such as a DropDownList:

foreach (var item in listControl.Items) {
    item.Value = string.empty;
}

The compiler considers item to be of type object. It works if I replace var with ListItem, declaring the variable explicitly. The Items property is a ListItemCollection, which implements IEnumerable. Shouldn't the compiler be able to tell that the objects in the collection are of type ListItem?

like image 508
kad81 Avatar asked Jan 28 '26 03:01

kad81


1 Answers

This is a strange behavior since, as you point out, ListItemCollection is a collection of ListItems. This appears related to the fact that this was implemented before C# supported generics. And so it implements IEnumerable instead of IEnumerable<ListItem>, and isn't able to determine the correct type.

I suggest rewriting your loop this way:

foreach (ListItem item in listControl.Items) {
    item.Value = string.empty;
}

Check out this question for additional information.

like image 152
Jonathan Wood Avatar answered Jan 30 '26 16:01

Jonathan Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!