Search code examples
c#visual-studio-2008refactoringresharpercode-snippets

Any way to surround code block with Curly Braces {} in VS2008?


I always find myself needing to enclose a block of code in curly braces { }, but unfortunately that isn't included in the C# surround code snippets, which seems to be an oversight. I couldn't find anything on building your own surround snippets either (just other kinds of snippets).

I am actually running Resharper too, but it doesn't seem to have this functionality either (or I haven't figured how to activate it).

We have a coding standard of including even a single line of code after an if or else in curly braces, so if I could just make Resharper do that refactoring automatically that would be even better!


Solution

  • Here is a quick and dirty snippet to do just that.

    To Install:

    Save the code as SurroundWithBraces.snippet into "<my documents>\Visual Studio Version\Code Snippets\Visual C#\My Code Snippets"

    To use:

    Select block of text.
    Press Ctrl+K, Ctrl+S
    Chose My Code Snippets, braces

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>braces</Title>
          <Shortcut>braces</Shortcut>
          <Description>Code snippet to surround a block of code with braces</Description>
          <Author>Igor Zevaka</Author>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
          </SnippetTypes>
        </Header>
        <Snippet>
          <Code Language="csharp">
            <![CDATA[{
            $selected$ $end$
         }]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>