Organize Your Code with Named Regions

Tips Search

If you like the tips then you'll love the book!

Order your copy today:
http://www.amazon.com/gp/product/0735649928

Organize Your Code with Named Regions

  • Comments 10

 

Versions: 2005, 2008, 2010

Code: vstipEdit0095

 

 

Did you know you can create named Regions that can be used to organize your code? Let’s take a look at how to do it.

 

Creating Named Regions

C++


In C++ you create regions by using “#pragma region” with label and “#pragma endregion” (case-specific):

image

 

 

C#

For C# you can eliminate the “pragma” keyword and just use “#region” with label and “#endregion” (case-specific):

image

 

 

VB

Visual Basic is just as easy as C# and uses a similar syntax of “#Region” with label and “#End Region” (not case-specific):

image

 

 

 

Value of Named Regions

The value of creating Regions is twofold. First, they travel with the code so are shared by all team members when using source control. Second, they become part of document outlining and can be collapsed or expanded to further organize you code:

image

  • Zain,

    FYI, named C# regions do not require quotes.

    Thanks,

    Scott Blomfield

  • Using regions is like putting the toilet lid down without flushing.

  • Scott -- Yeah i struggled with that one for a bit but decided to show them with quotes for consistency with the VB ones

    dkil1972 -- So...Regions are out for you? :)

  • You'd better watch out there Zain... you're liable to ruffle a few feathers. In my experience, developers have strong feelings (for and against) code regions ;)

  • Hehehe thanks Casey :)

    Thankfully I can claim to be a conscientious objector in this particular battle.  To paraphrase the Fox News tagline:  I report, you decide.

    Z

  • Yeah, I have to agree with dkil1972. Regions always seemed like toddler refactoring to me. I'll just push everything under this here... TADA! It's clean!

  • Large Code Regions = an excuse to not bother adhering to SRP :-)

  • Yeah... there are some really strong opinions about regions in source code.  Richard Banks has started an "Anti-Region Campaign" on his blog and he lists some reasons why he doesn't like them:  www.richard-banks.org/.../anti-region-campaign.html

  • I use resharper to autoblock all of my code into regions, region for using statements, region for members, fields, ctors, etc. This way you can collapse to outline and only need to expand the method or 2 you're actively developing. Most times things like using statements, fields, ctors and autoproperties are all just noise anyway.

  • Chris: How are you getting ReSharper to autoblock your code into regions?  I have ReSharper but haven't seen/found that.  I've been using nArrange to do it, but that tool is getting old and not working in all WPF code behind files.

Page 1 of 1 (10 items)
Leave a Comment
  • Please add 6 and 2 and type the answer here:
  • Post