What ReSharper 4+ live templates for C# do you use?

Viewed 12067

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

36 Answers

Simple Lambda

So simple, so useful - a little lambda:

Shortcut: x

Available: C# where expression is allowed.

x => x.$END$

Macros: none.

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

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

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.

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

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

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$

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

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)));

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$

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$))]

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.

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$

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
    // ...
}

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$

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.

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

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

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

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; }

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

Related