views:

57

answers:

3

Can I collapse foreach, using and other c# code blocks in Visual Studio 2010, the same way that I can collapse methods, properties, classes, namespaces, etc? It would be very helpful sometimes.

+2  A: 

You can use #region #endregion directives to create collapsible areas.

Update:

By the way, why do you need this functionality? There's good a principle to keep your methods as short as possible (Uncle Bob calls it extract until you drop). If you stick to it you won't need additional collapsible areas.

Andrew Bezzub
Good for short term, but I wouldn't want to leave them in the code. Thanks.
Ronnie Overby
A've added one more thought I got
Andrew Bezzub
I adhere to those principles, but sometimes there are atomic units of code that just run long and can't be or don't deserve to be broken down: when calling methods in an external API that has LOTS of parameters; when the chance of needing to reuse code is zero.
Ronnie Overby
+1  A: 

Cut + paste the code out of the foreach loop and into a function, collapse the function away?

E.g.,

public void MyMessyFunction()
{
  // ...

  foreach(string foo in bar)
  {
    // Do ugly stuff
  }

  // ...
}

Turns into

public void MyMessyFunction()
{
  // ...

  foreach(string foo in bar)
  {
    DoUglyStuff(foo, bar);
  }

  // ...
}

#region Stuff I want to hide

public void DoUglyStuff(string foo, List<string> bar)
{
  // Do ugly stuff
}

#endregion
mrnye
A: 

As I recall, you can collapse an arbitrary region in Visual Studio 2010. Try selecting a region, then press Ctrl+M twice (assuming C# key bindings).

In VS2008, this is found under Edit -> Outlining; I don't have a 2010 installed so can't try it out there readily.

Edit: Actually, it looks like VS2008 has something similar in its "Hide Selection" feature (found in the same place), but it appears to only be available in some languages.

Michael Kjörling