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.
With R#, you can create a Live Template. In this case:
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With