I often need to convert auto properties to full properties with a backing field so that I can implement INotifyPropertyChanged
. It gets very tedious when a class has 50+ properties.
public string MyProperty { get; set;}
to
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
I was able to create a code snippet that creates a new property in the above format, but I don't know if it is possible to pull in an existing property's name and type and replace it.
I saw kindofmagic but I really don't want to use arcane magic in my project.
This question explains how to do it in Resharper, but I don't have Resharper. I even downloaded the trial and still couldn't figure out how to do it.
Is there some way to do this with code snippets, macros, or even a free extension? It seems like it should be fairly straightforward.
An auto-implemented property is equivalent to a property for which the property value is stored in a private field. The following code example shows an auto-implemented property. The following code example shows the equivalent code for the previous auto-implemented property example.
properties allow your access to be polymorphic (inheritors can modify access if the property is virtual) if you so choose. auto-properties are nice when you're dealing with simple get/set operations. if you do more complicated operations inside your get / set, then you can't use the auto-property.
If you have notepad++, you could do it via RegEx (quite ugly, but works)
Find what: (public)\s+([a-zA-z0-9]+)\s+([a-zA-z0-9]+)\s*\{\s*+get;\s*set;\s*\}
Replace with: private \2 _\3\; \r\n \1 \2 \3 \r\n \{ \r\n get \{ return _\3\; \} \r\n set \{ _\3=value\; OnPropertyChanged\(\"\3\"\)\; \} \r\n \}
Make sure "Regular Expression" is checked
This is what the Find/Replace screen looks like:
And it goes from
To:
Edit: Thanks to Britton, here is the Visual Studio equivalent:
Find: public[^\S\r\n](.+)[^\S\r\n](\b(_\w+|[\w-[0-9_]]\w*)\b)[^\S\r\n]{[^\S\r\n]get;[^\S\r\n]set;[^\S\r\n]}
Replace: private $1 _$2;\r\npublic $1 $2 {\r\nget\r\n{\r\nreturn _$2;\r\n}\r\nset\r\n{\r\n_$2 = value; OnPropertyChanged("$2");\r\n}\r\n}
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