5

I have a lot of C# code that uses public fields, and I would like to convert them to properties.

I have Resharper, and it will do them one by one, but this will take forever.

Does anyone know of an automated refactoring tool that can help with this?

TWA
  • 12,756
  • 13
  • 56
  • 92

3 Answers3

8

Resharper does it very quickly, using Alt+PageDown / ALt+Enter (with the default key bindings). If you are at the first field, Alt+PageDown will jump to the next one (since it'll include wrapping public fields as a suggested refactoring), and Alt+Enter will prompt you to wrap it in a property.

Since you most likely want to avoid a full blanket wrapping of all properties, this is probably the quickest approach. It's quite fast to do this to a class, since it jumps exactly where you need to go...

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • When I press Alt+Enter I don't get the "Encapsulate Field" refactoring suggestion. I have to right click and use the refactor menu. I am using the default key bindings, and the latest release version (4.5.1231.7). – TWA Jun 22 '09 at 18:37
  • 2
    Ctrl+R/E is the direct refactoring you want. You could just do Alt+PageDown then Ctrl+R/E, and avoid the menu. I'm not sure why, but I get it as a suggested refactoring with the Alt+Enter menu... – Reed Copsey Jun 22 '09 at 18:42
3

Refactor fields to properties (no extensions needed):

Refactor C# fields to properties

Step 1: Refactor all fields to be encapsulated by properties

Step 2: Refactor all properties into auto-implemented properties

Josh Withee
  • 9,922
  • 3
  • 44
  • 62
0

If you're in VS.NET when you rename a field, VS prompts you to change all occurrences of the renamed field.

So change your public Variable to the property name, tell VS to change all the instances of this variable, then create a private variable to store the value and a public property of the Proper name. Delete the public Variable and you should be good to go.

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
rie819
  • 1,249
  • 12
  • 19
  • 1
    This is much slower than using resharper, or even Visual Studio's built in refactoring to wrap fields in properties. – Reed Copsey Jun 22 '09 at 18:26
  • 1
    This is useful if you're using the Express edition of Visual Studio, which does not support the "Encapsulate Field" refactoring. – Jan Hettich Mar 04 '14 at 02:24