Oct 222012
 

If there is need to iterate through ListView items, I often see following code:

foreach (var item in listView1.Items) {
    var itemX = (ListViewItem)item;
    //do something with itemX
}

Unfortunately C# compiler is not smart enough to notice that item is actually ListViewItem so it keeps it as Object. And thus we need to cast it to our desired type.

Well, actually there is no need to do this. One just needs to remember live before implicit typing with var came:

foreach (ListViewItem item in listView1.Items) {
    //do something with item
}

This still works and it definitely looks nicer.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>