views:

862

answers:

3

Hello,

I use the right button>Refactor>Encapsultate field to have my accessor every time. The problem is when I create new class, I can have more than 10 attributes and it's long to do 1 by 1 every accessor. Is there a faster way to create them?

Thank you for your time.

A: 

Looks like the refactoring built into studio only supports a single field at a time for the Encapsulate Field refactoring. Refactor Pro! (http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/) or Resharper (http://www.jetbrains.com/resharper/index.html) both have support for encapsulating multiple fields.

You may be able to get fancy and put together a macro that would allow you to select multiple fields and then encapsulate each one, but VS macros are not my ball of wax.

ckramer
How do you get resharper to do more than one at a time? If I hilite multiple private fields it greys out the encapsulate option.
mattlant
I haven't used Resharper in a while, so I may be thinking of the Generate Properties code generation feature (http://www.jetbrains.com/resharper/documentation/help20/AdvEditing/altInsertProp.html)
ckramer
+2  A: 

If you create a new class, you can use code snippets to create encapsulated fields instead of first creating field and then encapsulating it. In C#, the shortcuts are prop and propg (for private set).

alex
A: 

In C# 3.0, the new property syntax saves you the need to declare the field & implement the accessors. They syntax is looks like:

public string Name { get; private set; }

Also, I want to point out that for internal members, trivial properties have very little value over internal fields, since you have control over both caller and implementation - you can switch to a property in the future, without a lot of work.

Even for public members, thinking you can future-proof your code merely by making public data fields in to properties is myopic. At the very least, you should add indirection around your constructor (with a factory), and your interface (with an interface). It also requires deep thought in to how the consumers of your API will expect you to work over multiple versions. It's really hard, and it's only worth doing if you are an API vendor, in my opinion.

In my code, the main reason I use properties is because a lot of tools that use reflection look at properties but not fields. I think this is a mistake, but that's the way the tools work.

Jay Bazuzi