Friday, December 30, 2011

Make your code Speak by using C# Region

Shout it kick it on DotNetKicks.com
Post for the beginner developer or for the developer who want their code to speak and easy to understand to other developer who is going to maintain the code, review the code etc.

To achive this thing most of the people talks about commenting class,method, property etc.but no one talks about the making region in the code which make code compact and easy to understand in form of regions. Region allow to block of the code which you can expand and minimize.

Syntax to define the region in you code is
#region Properties
//your code
#endregion Properties
So above code defines the region with name Properties. What ever code you write between between region and endregion get minimize and expand in visual studio you can see the + when minimize and - when maximize the code block.

Example of the file with the region related to BAL or DAL layer of code  :

Example of Aspx file i.e presentation layer file

Why to use Region in your code
  • It allow to group the member which is related to same functionality 
    • For Example in above code : Insert/Update method , Get Method
  • It to group Class members (private, public, methods, properties, etc.) , which you can easily see in above image
  • With the help of region long code blocks can be minimize to small block, which you can expand when you want to see the code and minimize when work done with it.
SortCut keys and  Context menu for Region
  • Shortcut key for  region is (MSDN link for this : http://msdn.microsoft.com/en-us/library/td6a5x4s.aspx )
    • CTRL+M CTRL+M (that's two key presses!) - collapse/open the current parent region
    • CTRL+M CTRL+L - Collapse/Open all regions in document recursively (meaning you might get only one line in the document - one big namespace region which is collapsed or you'll see the entire page code uncollapsed
    • CTRL+M CTRL+O - Collapse all regions not recursively
  • You can also make use of Context menu for that in you text editor
When not to use Region in your code
  • To Hide 'ugly code' that is more complicated.
  • To hide misc. code so that lazy reviewers don't look and ask about that part of code.
  • Make region to hide the Commented code.

4 comments:

  1. Honourable bye, genial friend :)

    ReplyDelete
  2. Lofty bye, considerate alternative other :)

    ReplyDelete