http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

How to replace default interface property implementation expansion with automatic properties

By default, when you implement an interface in a class, you get the following for properties:

public string ClassName
{
    get
    {
        throw new NotImplementedException();
    }
    set
    {
        throw new NotImplementedException();
    }
}

But of course the typical thing to do is to implement them as automatic properties. You have two options at this point: modify the default expansion snippet, or do a find & replace with a regex.

How to change the default property stub expansion

Open the PropertyStub.snippet from C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring\PropertyStub.snippet, and change the <Code> from:

<Code Language="csharp">
    <![CDATA[$signature$
{
    $GetterAccessibility$ get
    {
        $end$throw new $Exception$();
    }
    $SetterAccessibility$ set
    {
        throw new $Exception$();
    }
}]]>
</Code>

to:

<Code Language="csharp">
    <![CDATA[$signature$ { get; set; }]]>
</Code>

 

Done. Now implementing an interface shields:

public string ClassName { get; set; }

How to replace default property expansion with a regular expression

Find: (?<member>\w+)\s*\{\s*get\s*\{\s*throw\snew\sNotImplementedException\(\);\s*\}\s*set\s*\{\s*throw\snew\sNotImplementedException\(\);s*\}\s*\}

Replace: ${member} { get; set; }

 

Use the Power Tools inline replace in the text editor (Ctrl + H) because the replacement string is in .NET Regex format.

Update: you can do the same trick (add automatic get; private set;) to interfaces that only have a getter defined (note the private set;), by changing the snippet at C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring\PropertyStubGet.snippet. I’ve both now in place, and doing interface-based programming (a good thing!) is now more enjoyable :) .

Comments

5 Comments

  1. [...] How to replace default interface property implementation expansion with automatic properties – Daniel Cazzulino takes a look at how you can customise the templates for the auto creation of properties in Visual Studio to allow you to have it generate auto properties. These principles apply to the templates for other expansions, allowing you to customise and improve your development experience. [...]

  2. Great tip. I didn’t consider doing this myself but I have been implementing some interfaces recently and been annoyed by this “feature”.

    As an aside I have actually change the insert automatic property snippet (prop) so that its default type is string instead of (I think) int. This seems to be the most common type for me so it saves a lot of time.

  3. Now we just need it to be virtual by default.