94

What ReSharper 4.0 templates for C# do you use?

Let's share these in the following format:


[Title]

Optional description

Shortcut: shortcut
Available in: [AvailabilitySetting]

// Resharper template code snippet
// comes here

Macros properties (if present):

  • Macro1 - Value - EditableOccurence
  • Macro2 - Value - EditableOccurence

Community
  • 1
  • 1
Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
  • Should this be on [programmers.SE](http://programmers.stackexchange.com/) instead because it’s subjective? – Timwi Apr 04 '11 at 17:07
  • This question is not constructive and there is a lot of information out there about resharper live templates and visual studio templates. http://programmingsolved.blogspot.com/2014/04/snippet-away.html – Thulani Chivandikwa Apr 24 '14 at 08:12

36 Answers36

31

Simple Lambda

So simple, so useful - a little lambda:

Shortcut: x

Available: C# where expression is allowed.

x => x.$END$

Macros: none.

Sean Kearon
  • 10,987
  • 13
  • 77
  • 93
22

Implement 'Dispose(bool)' Method

Implement Joe Duffy's Dispose Pattern

Shortcut: dispose

Available in: C# 2.0+ files where type member declaration is allowed

public void Dispose()
{
    Dispose(true);
    System.GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            if ($MEMBER$ != null)
            {
                $MEMBER$.Dispose();
                $MEMBER$ = null;
            }
        }

        disposed = true;
    }
}

~$CLASS$()
{
    Dispose(false);
}

private bool disposed;

Macros properties:

  • MEMBER - Suggest variable of System.IDisposable - Editable Occurence #1
  • CLASS - Containing type name
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32
Ed Ball
  • 1,979
  • 2
  • 14
  • 13
14

Create new unit test fixture for some type

Shortcut: ntf
Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

[NUnit.Framework.TestFixtureAttribute]
public sealed class $TypeToTest$Tests
{
    [NUnit.Framework.TestAttribute]
    public void $Test$()
    {
        var t = new $TypeToTest$()
        $END$
    }
}

Macros:

  • TypeToTest - none - #2
  • Test - none - V
Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
13

Check if a string is null or empty.

If you're using .Net 4 you may prefer to use string.IsNullOrWhiteSpace().

Shortcut: sne

Available in: C# 2.0+ where expression is allowed.

string.IsNullOrEmpty($VAR$)

Macro properties:

  • VAR - suggest a variable of type string. Editible = true.
Community
  • 1
  • 1
Sean Kearon
  • 10,987
  • 13
  • 77
  • 93
11

Create new stand-alone unit test case

Shortcut: ntc
Available in: C# 2.0+ files where type member declaration is allowed

[NUnit.Framework.TestAttribute]
public void $Test$()
{
    $END$
}

Macros:

  • Test - none - V
Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
10

Declare a log4net logger for the current type.

Shortcut: log

Available in: C# 2.0+ files where type member declaration is allowed

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof($TYPE$));

Macros properties:

  • TYPE - Containing type name
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32
Chris Brandsma
  • 11,666
  • 5
  • 47
  • 58
  • With re-sharper, why not use this? private static readonly ILog _Logger = LogManager.GetLogger(typeof($CurrType$)); with $CurrType$:Containing type name – Henrik Feb 16 '11 at 13:51
  • Because if I change the type name later on I would have to update that line of code as well. Mine is more dynamic. – Chris Brandsma Feb 23 '11 at 23:56
  • ReSharper automatically renames all instances of a type name. GetType() is slower too. – Richard Dingwall Sep 21 '11 at 13:07
9

MS Test Unit Test

New MS Test Unit test using AAA syntax and the naming convention found in the Art Of Unit Testing

Shortcut: testing (or tst, or whatever you want)
Available in: C# 2.0+ files where type member declaration is allowed

[TestMethod]
public void $MethodName$_$StateUnderTest$_$ExpectedBehavior$()
{
    // Arrange
    $END$

    // Act


    // Assert

}

Macros properties (if present):

  • MethodName - The name of the method under test
  • StateUnderTest - The state you are trying to test
  • ExpectedBehavior - What you expect to happen
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Vaccano
  • 78,325
  • 149
  • 468
  • 850
8

Check if variable is null

Shortcut: ifn
Available in: C# 2.0+ files

if (null == $var$)
{
    $END$
}

Check if variable is not null

Shortcut: ifnn
Available in: C# 2.0+ files

if (null != $var$)
{
    $END$
}
Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
7

Assert.AreEqual

Simple template to add asserts to a unit test

Shortcut: ae
Available in: in C# 2.0+ files where statement is allowed

Assert.AreEqual($expected$, $actual$);$END$

Fluent version :

Assert.That($expected$, Is.EqualTo($actual$));$END$
hdoghmen
  • 3,175
  • 4
  • 29
  • 33
Kjetil Klaussen
  • 6,266
  • 1
  • 35
  • 29
7

Write StyleCop-compliant summary for class constructor

(if you are tired of constantly typing in long standard summary for every constructor so it complies to StyleCop rule SA1642)

Shortcut: csum

Available in: C# 2.0+

Initializes a new instance of the <see cref="$classname$"/> class.$END$

Macros:

  • classname - Containing type name - V
Dmitrii Lobanov
  • 4,897
  • 1
  • 33
  • 50
7

Lots of Lambdas

Create a lambda expression with a different variable declaration for easy nesting.

Shortcut: la, lb, lc

Available in: C# 3.0+ files where expression or query clause is allowed

la is defined as:

x => x.$END$

lb is defined as:

y => y.$END$

lc is defined as:

z => z.$END$

This is similar to Sean Kearon above, except I define multiple lambda live templates for easy nesting of lambdas. "la" is most commonly used, but others are useful when dealing with expressions like this:

items.ForEach(x => x.Children.ForEach(y => Console.WriteLine(y.Name)));
g t
  • 7,287
  • 7
  • 50
  • 85
James Kovacs
  • 11,549
  • 40
  • 44
  • is it ok to use x,y names for lambda arguments? if you have two-three level nested lambdas, you probably don't want to memorize what does x,y,z means at each level. Considering your example, I would go with items.ForEach(item => ... and item.Children.ForEach(child => ... so that at the end I would have child.Name instead of y.Name. I don't think naming for lambdas arguments can be treated similary to for loop indexes i,j,k – Ilya Ivanov Dec 21 '12 at 11:32
6

Wait for It...

Pause for user input before end of a console application.

Shortcut: pause

Available in: C# 2.0+ files where statement is allowed

System.Console.WriteLine("Press <ENTER> to exit...");
System.Console.ReadLine();$END$
James Kovacs
  • 11,549
  • 40
  • 44
6

Dependency property generation

Generates a dependency property

Shortcut: dp
Available in: C# 3.0 where member declaration is allowed

public static readonly System.Windows.DependencyProperty $PropertyName$Property =
        System.Windows.DependencyProperty.Register("$PropertyName$",
                                                   typeof ($PropertyType$),
                                                   typeof ($OwnerType$));

    public $PropertyType$ $PropertyName$
    {
        get { return ($PropertyType$) GetValue($PropertyName$Property); }
        set { SetValue($PropertyName$Property, value); }
    }

$END$

Macros properties (if present):

PropertyName - No Macro - #3
PropertyType - Guess type expected at this point - #2
OwnerType - Containing type name - no editable occurence

Jonas Van der Aa
  • 1,441
  • 12
  • 27
5

Notify Property Changed

This is my favourite because I use it often and it does a lot of work for me.

Shortcut: npc

Available in: C# 2.0+ where expression is allowed.

if (value != _$LOWEREDMEMBER$)
{
  _$LOWEREDMEMBER$ = value;
  NotifyPropertyChanged("$MEMBER$");
}

Macros:

  • MEMBER - Containing member type name. Not editable. Note: make sure this one is first in the list.
  • LOWEREDMEMBER - Value of MEMBER with the first character in lower case. Not editable.

Usage: Inside a property setter like this:

private string _dateOfBirth;
public string DateOfBirth
{
   get { return _dateOfBirth; }
   set
   {
      npc<--tab from here
   }
}

It assumes that your backing variable starts with an "_". Replace this with whatever you use. It also assumes that you have a property change method something like this:

private void NotifyPropertyChanged(String info)
{
   if (PropertyChanged != null)
   {
      PropertyChanged(this, new PropertyChangedEventArgs(info));
   }
}

In reality, the version of this I use is lambda based ('cos I loves my lambdas!) and produces the below. The principles are the same as the above.

public decimal CircuitConductorLive
{
   get { return _circuitConductorLive; }
   set { Set(x => x.CircuitConductorLive, ref _circuitConductorLive, value); }
}

That's when I'm not using the extremely elegant and useful PostSharp to do the whole INotifyPropertyChanged thing for no effort, that is.

Sean Kearon
  • 10,987
  • 13
  • 77
  • 93
5

AutoMapper Property Mapping

Shortcut: fm

Available in: C# 2.0+ files where statement is allowed

.ForMember(d => d$property$, o => o.MapFrom(s => s$src_property$))
$END$

Macros:

  • property - editable occurrence
  • src_property - editable occurrence

Note:

I leave the lambda "dot" off so that I can hit . immediately and get property intellisense. Requires AutoMapper (http://automapper.codeplex.com/).

David R. Longnecker
  • 2,897
  • 4
  • 29
  • 28
5

Quick ExpectedException Shortcut

Just a quick shortcut to add to my unit test attributes.

Shortcut: ee

Available in: Available in: C# 2.0+ files where type member declaration is allowed

[ExpectedException(typeof($TYPE$))]
Community
  • 1
  • 1
womp
  • 115,835
  • 26
  • 236
  • 269
  • Just a quick note that it's been a couple version now that ExpectedException has been deprecated in NUnit in favor of using Assert.Throws<> – Stécy Jul 07 '11 at 18:01
  • Yes please please everyone stop using ExpectedExceptionAttribute, still see devs using MSTest use this even today :-( – bytedev Mar 16 '17 at 17:28
4

NUnit Setup method

Shortcut: setup
Available in: Available in: C# 2.0+ files where type member declaration is allowed

[NUnit.Framework.SetUp]
public void SetUp()
{
    $END$
}
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32
paraquat
  • 641
  • 6
  • 9
  • Good point. I can think of some cases where you might want to subclass test fixtures (perhaps if you wanted to write "contract" tests where a set of assertions should apply to a number of objects), but I think in the much more common case, virtual is superfluous. I'll edit it out. – paraquat Sep 30 '09 at 15:43
  • An improvement to this............private $classUnderTestType$ _classUnderTest; [NUnit.Framework.SetUp] public void SetUp() { _classUnderTest = new $classUnderTestType$($END$); } – bytedev Mar 16 '17 at 17:29
4

NUnit Teardown method

Shortcut: teardown
Available in: Available in: C# 2.0+ files where type member declaration is allowed

[NUnit.Framework.TearDown]
public void TearDown()
{
    $END$
}
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32
paraquat
  • 641
  • 6
  • 9
4

Create test case stub for NUnit

This one could serve as a reminder (of functionality to implement or test) that shows up in the unit test runner (as any other ignored test),

Shortcut: nts
Available in: C# 2.0+ files where type member declaration is allowed

[Test, Ignore]
public void $TestName$()
{
    throw new NotImplementedException();
}
$END$
Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
  • I do a variation on this, but with explicit Assert.Fail() in the body: http://aleriel.com/blog/2010/04/07/replace-paper-with-unit-tests/ – Adam Lear Apr 20 '10 at 17:24
4

New C# Guid

Generates a new System.Guid instance initialized to a new generated guid value

Shortcut: csguid Available in: in C# 2.0+ files

new System.Guid("$GUID$")

Macros properties:

  • GUID - New GUID - False
Community
  • 1
  • 1
codekaizen
  • 26,990
  • 7
  • 84
  • 140
4

Invoke if Required

Useful when developing WinForms applications where a method should be callable from non-UI threads, and that method should then marshall the call onto the UI thread.

Shortcut: inv

Available in: C# 3.0+ files statement is allowed

if (InvokeRequired)
{
    Invoke((System.Action)delegate { $METHOD_NAME$($END$); });
    return;
}

Macros

  • METHOD_NAME - Containing type member name

You would normally use this template as the first statement in a given method and the result resembles:

void DoSomething(Type1 arg1)
{
    if (InvokeRequired)
    {
        Invoke((Action)delegate { DoSomething(arg1); });
        return;
    }

    // Rest of method will only execute on the correct thread
    // ...
}
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
4

MSTest Test Method

This is a bit lame but it's useful. Hopefully someone will get some utility out of it.

Shortcut: testMethod

Available in: C# 2.0

[TestMethod]
public void $TestName$()
{
    throw new NotImplementedException();

    //Arrange.

    //Act.

    //Assert.
}

$END$
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Daver
  • 333
  • 2
  • 5
  • 14
3

Create sanity check to ensure that an argument is never null

Shortcut: eann
Available in: C# 2.0+ files where type statement is allowed

Enforce.ArgumentNotNull($inner$, "$inner$");

Macros:

  • inner - Suggest parameter - #1

Remarks: Although this snippet targets open source .NET Lokad.Shared library, it could be easily adapted to any other type of argument check.

Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
3

New COM Class

Shortcut: comclass

Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("$GUID$")]
public class $NAME$ : $INTERFACE$
{
    $END$
}

Macros

  • GUID - New GUID
  • NAME - Editable
  • INTERFACE - Editable
Ian G
  • 10,709
  • 6
  • 30
  • 34
3

Assert Invoke Not Required

Useful when developing WinForms applications where you want to be sure that code is executing on the correct thread for a given item. Note that Control implements ISynchronizeInvoke.

Shortcut: ani

Available in: C# 2.0+ files statement is allowed

Debug.Assert(!$SYNC_INVOKE$.InvokeRequired, "InvokeRequired");

Macros

  • SYNC_INVOKE - Suggest variable of System.ComponentModel.ISynchronizeInvoke
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
2

Trace - Writeline, with format

Very simple template to add a trace with a formatted string (like Debug.WriteLine supports already).

Shortcut: twlf
Available in: C# 2.0+ files where statement is allowed

Trace.WriteLine(string.Format("$MASK$",$ARGUMENT$));

Macros properties:

  • Argument - value - EditableOccurence
  • Mask - "{0}" - EditableOccurence
Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
1

New Typemock isolator fake

Shortcut: fake
Available in: [in c# 2.0 files where statement is allowed]

$TYPE$ $Name$Fake = Isolate.Fake.Instance();
Isolate.WhenCalled(() => $Name$Fake.)

Macros properties:
* $TYPE$ - Suggest type for a new variable
* $Name$ - Value of another variable (Type) with the first character in lower case

Karsten
  • 8,015
  • 8
  • 48
  • 83
1

Since I'm working with Unity right now, I've come up with a few to make my life a bit easier:


Type Alias

Shortcut: ta
Available in: *.xml; *.config

<typeAlias alias="$ALIAS$" type="$TYPE$,$ASSEMBLY$"/>

Type Declaration

This is a type with no name and no arguments

Shortcut: tp
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$"/>

Type Declaration (with name)

This is a type with name and no arguments

Shortcut: tn
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$" name="$NAME$"/>

Type Declaration With Constructor

This is a type with name and no arguments

Shortcut: tpc
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$">
  <typeConfig>
    <constructor>
        $PARAMS$
    </constructor>
  </typeConfig>
</type>

etc....

Bryce Fischer
  • 5,336
  • 9
  • 30
  • 36
1

log4net XML Configuration Block

You can import the template directly:

<TemplatesExport family="Live Templates">
  <Template uid="49c599bb-a1ec-4def-a2ad-01de05799843" shortcut="log4" description="inserts log4net XML configuration block" text="  &lt;configSections&gt;&#xD;&#xA;    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot; /&gt;&#xD;&#xA;  &lt;/configSections&gt;&#xD;&#xA;&#xD;&#xA;  &lt;log4net debug=&quot;false&quot;&gt;&#xD;&#xA;    &lt;appender name=&quot;LogFileAppender&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;&#xD;&#xA;      &lt;param name=&quot;File&quot; value=&quot;logs\\$LogFileName$.log&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;AppendToFile&quot; value=&quot;false&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;RollingStyle&quot; value=&quot;Size&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaxSizeRollBackups&quot; value=&quot;5&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaximumFileSize&quot; value=&quot;5000KB&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;StaticLogFileName&quot; value=&quot;true&quot; /&gt;&#xD;&#xA;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%date [%3thread] %-5level %-40logger{3} - %message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;appender name=&quot;ConsoleAppender&quot; type=&quot;log4net.Appender.ConsoleAppender&quot;&gt;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;root&gt;&#xD;&#xA;      &lt;priority value=&quot;DEBUG&quot; /&gt;&#xD;&#xA;      &lt;appender-ref ref=&quot;LogFileAppender&quot; /&gt;&#xD;&#xA;    &lt;/root&gt;&#xD;&#xA;  &lt;/log4net&gt;&#xD;&#xA;" reformat="False" shortenQualifiedReferences="False">
    <Context>
      <FileNameContext mask="*.config" />
    </Context>
    <Categories />
    <Variables>
      <Variable name="LogFileName" expression="getOutputName()" initialRange="0" />
    </Variables>
    <CustomProperties />
  </Template>
</TemplatesExport>
Igor Brejc
  • 18,714
  • 13
  • 76
  • 95
1

Make Method Virtual

Adds virtual keyword. Especially useful when using NHibernate, EF, or similar framework where methods and/or properties must be virtual to enable lazy loading or proxying.

Shortcut: v

Available in: C# 2.0+ file where type member declaration is allowed

virtual $END$

The trick here is the space after virtual, which might be hard to see above. The actual template is "virtual $END$" with reformat code enabled. This allows you to go to the insert point below (denoted by |) and type v:

public |string Name { get; set; }
James Kovacs
  • 11,549
  • 40
  • 44
1

Equals

Neither .NET in general nor the default “equals” template make it easy to bang out a good, simple Equals method. While there are many thoughts on how to write a good Equals method, I think the following suffices for 90% of simple cases. For anything more complicated — especially when it comes to inheritance — it might be better to not use Equals at all.

Shortcut: equals
Available in: C# 2.0+ type members

public override sealed bool Equals(object other) {
    return Equals(other as $TYPE$);
}

public bool Equals($TYPE$ other) {
    return !ReferenceEquals(other, null) && $END$;
}

public override int GetHashCode() {
    // *Always* call Equals.
    return 0;
}

Macros properties:

  • TYPE - Containing type name - Not Editable
Community
  • 1
  • 1
Michael Kropat
  • 14,557
  • 12
  • 70
  • 91
0

Rhino Mocks Record-Playback Syntax

Shortcut: RhinoMocksRecordPlaybackSyntax *

Available in: C# 2.0+ files

Note: This code snippet is dependent on MockRepository (var mocks = new new MockRepository();) being already declared and initialized somewhere else.

using (mocks.Record())
{
    $END$
}

using (mocks.Playback())
{

}

*might seem a bit long for a shortcut name but with intellisense not an issue when typing. also have other code snippets for Rhino Mocks so fully qualifying the name makes it easier to group them together visually

Ray
  • 187,153
  • 97
  • 222
  • 204
0

Rhino Mocks Expect Methods

Shortcut: RhinoMocksExpectMethod

Available in: C# 2.0+ files

Expect.Call($EXPECT_CODE$).Return($RETURN_VALUE$);

Shortcut: RhinoMocksExpectVoidMethod

Available in: C# 2.0+ files

Expect.Call(delegate { $EXPECT_CODE$; });
Ray
  • 187,153
  • 97
  • 222
  • 204
0

Borrowing from Drew Noakes excellent idea, here is an implementation of invoke for Silverlight.

Shortcut: dca

Available in: C# 3.0 files

if (!Dispatcher.CheckAccess())
{
    Dispatcher.BeginInvoke((Action)delegate { $METHOD_NAME$(sender, e); });
    return;
}

$END$

Macros

  • $METHOD_NAME$ non-editable name of the current containing method.
jhappoldt
  • 2,406
  • 1
  • 21
  • 24
0

Machine.Specifications - Because of

As a heavy mspec user, I have several live templates specifically for MSpec. Here's a quick one for setting up a because and catching the error.

Shortcut: bece
Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

bece - Because of (with exception catching)

Protected static Exception exception;
Because of = () => exception = Catch.Exception(() => $something$);
$END$
David R. Longnecker
  • 2,897
  • 4
  • 29
  • 28
0

Machine.Specifications - It

Shortcut: it

Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

Machine.Specifications.It $should_$ =
    () => 
    {

    };

Macros properties (if present):

  • should_ - (No Macro) - EditableOccurence
Richard Dingwall
  • 2,692
  • 1
  • 31
  • 32