2

I created the following simple Snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Observable Property</Title>
      <Description>Generates an Observable property based on type and Name</Description>
      <Shortcut>nosp</Shortcut>
    </Header>

    <Snippet>
      <Declarations>
        <Literal>
          <ID>PropertyName</ID>
          <ToolTip>Defines the Property Name</ToolTip>
          <Default>Name</Default>
        </Literal>
        <Literal>
          <ID>PropertyType</ID>
          <Type>Type</Type>
          <ToolTip>Defines the Property Type</ToolTip>
          <Default>String</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
        public $PropertyType$ $PropertyName$
        {
            get { return Get<$PropertyType$>("$PropertyName$"); }
            set
            {
                Set("$PropertyName$", value);
            }
        }               
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

And its working as expected to create for example

    public VirtualKeyCode Key
    {
        get { return Get<VirtualKeyCode>("Key"); }
        set
        {
            Set("Key", value);
        }
    }

Is it possible to change all $PropertyType$ locations when one of them is changed after the initial insertion of the snippet for example during refactoring ?

1
  • Answered, but no Check mark for @Jereon? Commented Feb 7, 2020 at 0:31

1 Answer 1

2

No. A snippet is just a quick way to produce text. VS loses all knowledge and context about it once it's inserted. You could, of course, simply insert the snippet anew with the correct type, but there's no way for any refactoring to know the code came from a snippet.

If you're feeling particularly ambitious, you could take a crack at writing a Roslyn extension that tracks which code parts come from snippet variables, and make a snippet-aware refactoring that changes all variable instances. Even so this couldn't work across sessions unless you make snippets tag code with a comment (// snippet: Observable Property), or (if you're feeling really ambitious) you actively match code against snippets whether or not they originally came from snippets, and operate on the matched trees. While powerful, it could lead to surprises if someone is really trying to change only part of the code.

...so the short answer is no.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.