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

C#TemplatesRefactoringResharper

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Simple Lambda

So simple, so useful - a little lambda:

Shortcut: x

Available: C# where expression is allowed.

x => x.$END$

Macros: none.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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.

Solution 5 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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

Solution 9 - C#

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$

Solution 10 - C#

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

Solution 11 - C#

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

Solution 12 - C#

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$

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

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.

Solution 16 - C#

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

Solution 17 - C#

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$

Solution 18 - C#

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

Solution 19 - C#

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$

Solution 20 - C#

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

Solution 21 - C#

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

Solution 22 - C#

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

Solution 23 - C#

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.

Solution 24 - C#

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

Solution 25 - C#

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

Solution 26 - C#

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

Solution 27 - C#

New Typemock isolator fake

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

$TYPE$ $Name$Fake = Isolate.Fake.Instance<$TYPE$>();
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

Solution 28 - C#

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

Solution 29 - C#

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>

Solution 30 - C#

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

Solution 31 - C#

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

Solution 32 - C#

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

Solution 33 - C#

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

Solution 34 - C#

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.

Solution 35 - C#

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$

Solution 36 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRinat AbdullinView Question on Stackoverflow
Solution 1 - C#Sean KearonView Answer on Stackoverflow
Solution 2 - C#Ed BallView Answer on Stackoverflow
Solution 3 - C#Rinat AbdullinView Answer on Stackoverflow
Solution 4 - C#Sean KearonView Answer on Stackoverflow
Solution 5 - C#Rinat AbdullinView Answer on Stackoverflow
Solution 6 - C#Chris BrandsmaView Answer on Stackoverflow
Solution 7 - C#VaccanoView Answer on Stackoverflow
Solution 8 - C#Chris DoggettView Answer on Stackoverflow
Solution 9 - C#Kjetil KlaussenView Answer on Stackoverflow
Solution 10 - C#Dmitrii LobanovView Answer on Stackoverflow
Solution 11 - C#James KovacsView Answer on Stackoverflow
Solution 12 - C#James KovacsView Answer on Stackoverflow
Solution 13 - C#Jonas Van der AaView Answer on Stackoverflow
Solution 14 - C#wompView Answer on Stackoverflow
Solution 15 - C#Sean KearonView Answer on Stackoverflow
Solution 16 - C#David R. LongneckerView Answer on Stackoverflow
Solution 17 - C#Rinat AbdullinView Answer on Stackoverflow
Solution 18 - C#Drew NoakesView Answer on Stackoverflow
Solution 19 - C#DaverView Answer on Stackoverflow
Solution 20 - C#paraquatView Answer on Stackoverflow
Solution 21 - C#paraquatView Answer on Stackoverflow
Solution 22 - C#codekaizenView Answer on Stackoverflow
Solution 23 - C#Rinat AbdullinView Answer on Stackoverflow
Solution 24 - C#Ian GView Answer on Stackoverflow
Solution 25 - C#Drew NoakesView Answer on Stackoverflow
Solution 26 - C#Ray HayesView Answer on Stackoverflow
Solution 27 - C#KarstenView Answer on Stackoverflow
Solution 28 - C#Bryce FischerView Answer on Stackoverflow
Solution 29 - C#Igor BrejcView Answer on Stackoverflow
Solution 30 - C#James KovacsView Answer on Stackoverflow
Solution 31 - C#Michael KropatView Answer on Stackoverflow
Solution 32 - C#RayView Answer on Stackoverflow
Solution 33 - C#RayView Answer on Stackoverflow
Solution 34 - C#jhappoldtView Answer on Stackoverflow
Solution 35 - C#David R. LongneckerView Answer on Stackoverflow
Solution 36 - C#Richard DingwallView Answer on Stackoverflow