Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert auto property to full property

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.

like image 470
Britton Avatar asked Apr 29 '14 15:04

Britton


People also ask

What is the difference between a property and an auto implemented property?

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.

What is the point of auto properties?

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.


1 Answers

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: FindReplaceImg

And it goes from

StartImg

To:

EndImg

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}

like image 150
Dan Avatar answered Sep 28 '22 09:09

Dan