harry180 harry180 - 3 months ago 9
C# Question

Automatically create #region with same name at #endregion

I'm wondering if there is a way to make

#region Some Region #endregion Some Region
.
If there is no way for doing it then maybe is it possible with Resharper?

Hope it's clear what I'm trying to achive here.

Edit:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>#region</Title>
<Shortcut>#region</Shortcut>
<Description>Code snippet for #region</Description>
<Author>Microsoft Corporation</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 $name$
$selected$ $end$
#endregion $name$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


Second edit:
It's work but only when I make insert snippet. From intellisense this using some other snippet I gues.

So is there a way to add my region from intellisense not from insert snippet menu?

Answer

If what you are trying to acheive is...

#region MyRegion
//...lots of code...
#endregion // end of MyRegion

You can do this with a so-called 'SurroundsWith' snippet. Here is such a snippet from my library...

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0"    
   xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Enregions a block of code</Title>
    <Author>GJV</Author>
    <Shortcut>enr</Shortcut>
    <Description>Surrounds a block of code with region directives</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal Editable="True">
        <ID>RegionName</ID>
        <ToolTip>Region Name</ToolTip>
        <Default>MyRegion</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">  
    <![CDATA[
    #region $RegionName$
    $end$         
    $selected$    
    #endregion // end of $RegionName$ 
    ]]>        
    </Code>
  </Snippet>
</CodeSnippet>

To use it in Visual Studio, put the snippet in a .snippet file and save it in your snippets directory, then go to Tools => Code Snippets Manager => Add. Once it's added, you can use the standard CTRK K+X to access it.

The only thing this gives you over the built-in snippet for region is the flexibility to add the trailing comment to indicate the region's end. You can also further customise this by adding additional expansions.

NOTE: the sentinal $end$ marks where you want the cursor to land when the operation is complete.