Is it possible to write code template or a snippet which will do following:
I have a property declared like this:
public string String1 {get;set;}
And I want reshaprer to automatically generate following:
private string _string1;
public string String1
{
get
{
return _string1;
}
set
{
if (_string1 != value)
{
_string1 = value;
RaisePropertyChanged(() => String1);
}
}
}
Just have read the http://koder.wordpress.com/2010/03/25/resharper-inotifypropertychanged/ article and have created new live template which can insert code for a new property like I want it to be.
Is it possible to setup this template in such way, that it can appear in the Alt+Enter menu like a suggestion when cursor on the declaration of a property
Like:
{Access modifiers} **{Type} {Name}** {Possible get;set; statements}
This is the live template I came up with, I assigned 'npp' to initiate it. I don't think that you can Ctrl-Shift-R and replace it, but you can delete the old property declaration line and type 'npp' to invoke the template.
private $TYPE$ $NAME1$;
public $TYPE$ $NAME2$
{
get
{
return $NAME1$;
}
set
{
if ($NAME1$ == value) return;
$NAME1$ = value;
RaisePropertyChanged(() => $NAME1$);
}
}
I've created a slightly different custom template (ReSharper > Options > Code Inspection > Custom Patterns)
Search pattern:
public $Type$ $Pname$
{
get { return $FName$; }
set { $FName$ = value; }
}
Replace pattern:
public $Type$ $Pname$
{
get { return $FName$; }
set { $FName$ = value; NotifyOnPropertyChanged(() => $Pname$); }
}
And my workflow is the following for the already created auto-properties:
It's not the best solution but it works for me.
If you want this as a code inspection and a quick-fix, you can create a structural replace pattern. Go to ReSharper > Options > Code Inspection > Custom Patterns, click Add Pattern, and enter the following:
Search pattern:
public $type$ $name$ {get;set;}
where $type$ is a type placeholder of type System.Object or derived, and $name$ is an identifier placeholder.
Replace pattern:
private string _$name$;
public string $name$
{
get
{
return _$name$;
}
set
{
if (_$name$ != value)
{
_$name$ = value;
RaisePropertyChanged(() => $name$);
}
}
}
Set Pattern Severity to a particular severity level, which influences how ReSharper highlights matches in the text editor. Optionally, enter description for both patterns so that search pattern description focuses on the problem (i.e. "This regular property is suspicious") and replace pattern description focuses on solving the problem (i.e. "Replace with INotifyPropertyChanged implementation") Click Add, and you should be done.
Now there are two problems with this approach:
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