When using the Visual Studio shortcut/snippets is it possible to specify the collection in advance/automagically, rather than fill in the green boxes afterwards?
In this case, I’m trying to come up with something like the following with the fewest possible number of keystrokes:
foreach (ListItem item in ListBox1.Items)
{
//
}
For example, the shortcut “CTRL+K, CTRL+X foreach” takes a guess at what collection I want to iterate over, and normally gets it wrong. I often end up with the following:
foreach (object var in collection_to_loop)
{
//
}
If I type the collection identifier and/or use “Surround with” it doesn’t work any better, as it puts the highlighted item in the loop block as so:
foreach (ListItem item in ListBox1.Items)
{
ListBox1.Items
}
Is there a way to do this? I’m using Visual Studio 2005, but would be just as happy to be told this can be done in 2008, or with a plugin.
EDIT: OK it seems, not only did I not explain what I was after clearly, I was seeing a Resharper feature, and thinking it was a built in VS feature. It turns out it’s a Resharper “Live Templates” that’s making a spirited attempt at guessing what collection type to put into the loop, and getting it right about 1/4 of the time.
What I was after was a little insight into how Resharper makes that guess, and what I could do (such as highlighting the identifier of of my desired collection) to give it a hint. I’ll have a look at the Jetbrains website and update here if I find anything.
Type “ListBox1.Items” using normal intellisense, then hit Alt-Enter and choose “Enumerate collection with foreach” (not exact text).
However, speaking exactly about ListBox.Items (from Windows.Forms), it is of type ObjectCollection, which is not strongly typed. So it is almost impossible to guess correct type for elements. For WPF, Items property also returns non-strongly typed collection, ItemCollection. If you have strongly typed or generic collection, ReSharper can infer enumeration item type correctly.