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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With