Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we generate getters and setters in Visual Studio?

By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s).

But any more explicit explication or comment on good practice is welcome.

like image 353
Paul Avatar asked Aug 06 '08 02:08

Paul


People also ask

How do I generate a getter and setter in Visual Studio code?

The shortcut is Ctrl+Shift+R after highlighting the property. Longer method: Right click on the property. Then click on refactor from the popup menu. Currently, vscode has no feature to mass generate getters and setters for all class properties at once like in other IDEs so it has to be done one property at a time.

How do you implement getters and setters in C#?

It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


2 Answers

Rather than using Ctrl + K, X you can also just type prop and then hit Tab twice.

like image 153
Orion Edwards Avatar answered Sep 17 '22 09:09

Orion Edwards


Visual Studio also has a feature that will generate a Property from a private variable.

If you right-click on a variable, in the context menu that pops up, click on the "Refactor" item, and then choose Encapsulate Field.... This will create a getter/setter property for a variable.

I'm not too big a fan of this technique as it is a little bit awkward to use if you have to create a lot of getters/setters, and it puts the property directly below the private field, which bugs me, because I usually have all of my private fields grouped together, and this Visual Studio feature breaks my class' formatting.

like image 38
Dan Herbert Avatar answered Sep 17 '22 09:09

Dan Herbert