Visual Studio Snippets - How to Specify a Foreach Loop Collection
When using Visual Studio shortcut / snippets, is it possible to pre-specify the collection / automatically, rather than filling in the green boxes after?
In this case, I'm trying to come up with something like the following with the least number of keystrokes:
foreach (ListItem item in ListBox1.Items)
{
//
}
For example, the shortcut "CTRL + K, CTRL + X foreach" makes it possible to guess which collection I want to iterate over and is generally wrong. I often get the following:
foreach (object var in collection_to_loop)
{
//
}
If I type in the collection ID and / or use "Surround with" it doesn't work any better as it puts the selected item in the loop block like so:
foreach (ListItem item in ListBox1.Items)
{
ListBox1.Items
}
Is there a way to do this? I am using Visual Studio 2005 but am just as happy that it can be done in 2008 or with a plugin.
EDIT: OK, it looks like not only did I not explain what I was after, I saw the Resharper function and thought it was a built-in VS function. It turns out to be the Resharper "Live Templates", which makes a vigorous attempt to guess what type of collection will be put into the loop and get it right about 1/4 of the time.
What I found out was a little understanding of how Resharper makes this assumption and what I can do (for example, highlight the id of my desired collection) to give it a hint. I'll take a look at the Jetbrains site and update here if I find anything.
a source to share
Enter "ListBox1.Items" using normal intellisense, then press Alt-Enter and select "Enumerate collection with foreach" (not the exact text).
However, speaking specifically of ListBox.Items (from Windows.Forms) it is of type ObjectCollection, which is not strongly typed. Therefore, it is almost impossible to guess the correct type for the elements. For WPF, the Items property also returns a non-strongly typed ItemCollection. If you have a strongly typed or shared collection, ReSharper can correctly specify the type of the enumeration item.
a source to share
I really don't quite understand how to say this, but do you think you might be asking for too much automation? I mean code snippets are good because they reduce repetitive typing. But now you want to actually guess what you are going to type. Should he guess the body of the loop?
You might want to look into CodeRush Developer Express , which has a much more powerful code generation feature, but I'm not sure if it can do what you suggest.
a source to share