Search code examples
c#code-snippets

C# Code Snippet literal not expanding correctly


I'm facing a strange issue trying to build a custom code snippet around a simple Guard class that does the argument checks.

Guard Class

public sealed class Guard
{
    public static void Null(string paramName, object value)
    {
        if (value == null) throw new ArgumentNullException(paramName);
    }
}

Code Snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
<Header>
  <Title>Guard Guid Check</Title>
  <Author>Chris Richner</Author>
  <Description></Description>
  <HelpUrl></HelpUrl>
  <SnippetTypes />
  <Keywords />
  <Shortcut>gg</Shortcut>
</Header>
<Snippet>
  <References />
  <Imports>
    <Import>
      <Namespace>Foundation</Namespace>
    </Import>
  </Imports>
  <Declarations>
    <Literal Editable="true">
      <ID>argument</ID>
      <Type>System.Guid</Type>
      <ToolTip />
      <Default></Default>
      <Function />
    </Literal>
  </Declarations>
  <Code Language="csharp" Kind="" Delimiter="$"><![CDATA[Guard.Guid(nameof($argument$), $argument$);$selected$$end$]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Should generate the following code

Guard.Null(nameof(arg), arg);

But this is not working because only the first argument$ literal is highlighted in Visual Studio 2015 RTM Code Editor and finally filled with the given argument name.

What do I miss? Thanks!


Solution

  • Try the following.

    <CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <Header>
        <Title>Guard Guid Check</Title>
        <Author>Chris Richner</Author>
        <Shortcut>gg</Shortcut>
        <Description></Description>
        <SnippetTypes>
          <SnippetType>Expansion</SnippetType>
          <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
      </Header>
      <Snippet>
        <Declarations>
          <Literal>
            <ID>argument</ID>
            <ToolTip>Enter argument name</ToolTip>
            <Default>argument</Default>
          </Literal>
        </Declarations>
        <Code Language="CSharp"><![CDATA[
        Guard.Null(nameof($argument$), $argument$);
        ]]></Code>
      </Snippet>
    </CodeSnippet>
    

    Looking through your code there are some things that I dont recognize. 1) I am not sure what the $selected$$end$ are for and 2) I am not sure if the language property (csharp) is case sensitive.

    I took your information and placed it in a snippet that I know works correctly from VS 2005 to VS 2013. Then I tested the snippet and it worked correctly for me.