Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate readonly field for property with ReSharper

Since I didn't find whether is ReSharper capable of generating a private readonly backing field for a property, is there a way how to define custom script that could do that?

Imagine you have a property

public Type PropertyName { get; set; }

and then you set a cursor on this line, press Alt+Enter and there would be a menu item which transforms the property to

private readonly Type propertyName;

public Type PropertyName { get { return propertyName; } }

I have found myself in the situation where I would actually use this many times.

like image 537
Ondrej Janacek Avatar asked Nov 01 '13 16:11

Ondrej Janacek


2 Answers

With R#, you can create a Live Template. In this case:

  1. ReSharper > Templates Explorer
  2. Live Templates Tab > New Template (small grid icon)
  3. Shorcut: propReadOnly (this will be the shortcut used with intellisense)
  4. Description: whatever works for you...
  5. Available: in C# 2.0 where type member declaration is allowed
  6. Create the template as:

    private readonly $Type$ $propertyName$;

    public $Type$ $PropertyName$ { get { return $propertyName$; } }

Enclosing text in $SomeText$ will designate that text as a variable for R# to maninpulate.

In the variable name panel:

Name             Value             Editable Occurence
Type             Choose Macro*     #2
PropertyName     Choose Macro*     checkbox is checked
propertyName     (see below)       not editable
                 Macro > - Value of annother variable with the first character in lower case
                         - Select "PropertyName" as the other variable

*Choose Macro is displayed when no macro is selected; this is the default setting

Save and you can use the template immediately in Visual Studio by typing the shortcut used, i.e., "propReadOnly"

like image 121
Metro Smurf Avatar answered Oct 23 '22 09:10

Metro Smurf


You could work the other way around with ReSharper.

Create your private readonly backing field:

private readonly Type propertyName;

Then press alt + insert to generate the property.

Also see: Generating Properties

Edit:

Another option is to first create a property like this:

public MyProperty PropertyName { get { return propertyField;  } }

Then press alt + enter with your cursor on the fieldName to create the field. You will then jump to the field and by pressing alt + enter again Resharper will make it a Constructor parameter. Last but not least you'll now get the option to press alt + enter again to make the field readonly.

like image 40
Jos Vinke Avatar answered Oct 23 '22 11:10

Jos Vinke