13

My team absolutely loves using regions, and with that in mind it's pretty much become a de-facto standard in our code. I recently came to realization that I'm sick of writing or ctrl+c / ctrl+v'ing these in every time I create a class, test method, etc...

I was wondering if it is possible (via macros or some other functionality) to have Visual Studio automatically add these into your code.

For example, If I add a new class file to my project, can you perform some sort of magic to have visual studio generate the file as:

namespace Test
{
    class MyClass
    {
        #region ------------ members --------------
        #endregion

        #region ------------ properties --------------
        #endregion

        #region ------------ methods --------------
        #endregion
    }
}

Where I really get annoyed by not currently knowing how to do this, is when I'm writing unit tests. This may be a bit trickier, but I was trying to find a way to add --set up-- and --run test-- regions automatically to test methods because our team is adamant about using them.

So, when I go to create a new test method

[TestMethod]
public void WhenCondition_WillProduceExpectedResult()
{
}

Visual Studio would automatically add these two regions to the method, such as:

[TestMethod]
public void WhenCondition_WillProduceExpectedResult()
{
   #region ------------- set up -------------
   #endregion 

   #region ------------- run test -------------
   #endregion 
}

Not sure if this can be done, and if it can, whether it'd be via a vs-macro, or extension. Any help is much appreciated!

one noa
  • 345
  • 1
  • 3
  • 10
Eric Stallcup
  • 379
  • 2
  • 5
  • 15
  • 7
    Regions are a really bad code smell. If you need regions then your classes are probably way too big. – Dennis Traub Nov 26 '12 at 15:11
  • 1
    I find Ctrl C and Ctrl V very useful ;-) – user1725145 Nov 26 '12 at 15:11
  • 7
    @Dennis regions don't compile. They're just for readability and organisation, how is that code smell? – Amicable Nov 26 '12 at 15:16
  • Using a class template might achieve what you want. You could also write a macro to do this. You would also write an add-on if you wanted. Outside a specific question I don't see this being on topic since it seems your polling for solutions. – Security Hound Nov 26 '12 at 15:18
  • @Amicable he just told you: "If you need regions then your classes are probably way too big" <= Bad code smell... – C. Augusto Proiete Nov 26 '12 at 15:19
  • 3
    @Amicable read this by Jeff Atwood, one of the creators of this very website: http://www.codinghorror.com/blog/2008/07/the-problem-with-code-folding.html – Dennis Traub Nov 26 '12 at 15:20
  • 3
    Regardless of how much I might like or dislike regions, the important part is I am a member of a team that has adopted them as a standard. – Eric Stallcup Nov 26 '12 at 15:20
  • and @S List, that's what I'm currently doing...I guess I could stop being so finicky and just continue with the CTRL+C/CTRL+V'ing :) – Eric Stallcup Nov 26 '12 at 15:22
  • 1
    @Amicable oh, and comments don't compile either. – Dennis Traub Nov 26 '12 at 15:25
  • I would at least bring up the concerns raised here about using regions for every test method or class. I have found that external(outside of team/company) standards are always more beneficial than internal(inside of team/company) standards. – Ryan Gates Nov 26 '12 at 15:26
  • While I love Jeff's stuff and have been reading him for years, I categorically disagree with that article. regions allow you to see the overall code structure without being lost in the details. it's down to taste. that said, they can be overused. – Ben McIntyre Jun 09 '21 at 03:22

8 Answers8

22

You could create a simple code snippet like the following one:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Simple</Title>
      <Shortcut>simple</Shortcut>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Replace with the name of the action</ToolTip>
          <Default>Action</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
        public void $name$()
        {
            #region ------------- set up -------------
            #endregion 

            #region ------------- run test -------------
            #endregion 
        }
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Save that file into C:\Users\<your_user>\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets.

Now you just need to reopen Visual Studio, type 'simple' into a class and press Tab key twice.

Glauco Vinicius
  • 2,527
  • 3
  • 24
  • 37
  • 1
    +1 for the solution to OP's question. Of course automating bad habits makes it even more difficult to finally getting rid of them. – Dennis Traub Nov 26 '12 at 15:50
  • ReSharper "Remove region/endregion in solution" will automatically kill this bad habit and something like StyleCop with a rule to not use regions. :) – Maxime Rouiller Mar 10 '16 at 18:46
4

Two ways I know:

Create a snippet as per this MSDN guide.

Downloading the Visual Studio Extension Productivity Power Tools which has a "Surround" feature. This surrounds the user made selection with the selected snippet, for example #region #endregion or if statement.

Amicable
  • 3,115
  • 3
  • 49
  • 77
3

Don't know why so many people speak out against regions; they help me categorize my code very easily. What I use is a macro placed on one of my keyboard buttons that automatically inserts the regions for me. One tip I can give you is to put a small delay between each keypress if this is possible because VS sometimes misses characters otherwise.

Hope this helps!

TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101
2

Use the following snippet

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>#Classregion</Title>
      <Shortcut>#Classregion</Shortcut>
      <Description>Code snippet for #Classregion</Description>
      <Author>Author Name</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Region name</ToolTip>
          <Default>MyRegion</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
        #region ------------- Members ---------------
        $selected$ $end$
    #endregion

  #region --------------- Properties ---------------
        $selected$ $end$
    #endregion

  #region --------------- Methods ---------------
        $selected$ $end$
    #endregion
    ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Save it under C:\Users\\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets

Later it will be accessible in C# code, by Right-Click > Insert Snippet > My Code Snippets > #Classregion

Krishna
  • 170
  • 7
2

I prefer editing the class template as described in Sam Harwell's answer:

https://stackoverflow.com/a/2072717

You can open the class.cs file at your Visual Studio version's class template location. For example, Visual Studio 2017 Enterprise's location is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs

I open that file using a text editor and add regions to it. All new classes will then be created with the regions.

1

If you have Resharper then the File Structure window is very handy for managing regions, allowing simple drag and drop to move blocks of methods/properties etc. around. It shows your regions (which are collapsible) & syncs with the main code view too:

https://www.jetbrains.com/help/resharper/Reference__Windows__File_Structure_Window.html

eg A region called preview shown here:

Here

rexall
  • 101
  • 1
  • 4
0

And I agree that regions a are a bad idea but to each his own.

You might want to take a look at NArrange.

chrissie1
  • 5,014
  • 3
  • 26
  • 26
0

Late to the party but for anyone coming to this question in future like me,

It's possible in Visual Studio using CodeMaid Extension at least in VS2022.

After installing the extension go to options of code maid and enable Insert new regions.

enter image description here

After enabling it you need to use Reorganize document on your class and it does the job very well.

Reorganize Active Document

ibrahimijc
  • 331
  • 3
  • 12