Refactoring – a new feature in the Visual C# 2.0 IDE
Generating get/set accessors for variables
One of the practices that should be followed while programming, is that variables should rarely be made public.
If a variable needs to be accessed / modified by other classes, you should expose properties for doing so. This way, within the SET property, you can perform any validation, and thus prevent invalid values being assigned to your variables.
So, for a variable "username", you would write code like:
private string username;
public string Username
{
get { return username; }
set
{
//perform any validation if needed
username = value;
}
}
Man, that's a lot of code for one variable! Assume you ha to add 30-40 variables in your class, you'd spend a really long amount of time writing the get / set properties for each.
Here's where the C# 2005 IDE can help you out. What you can do is, initially, just add the variables (without the get and set properties). Then, right click on each variable for which you want to control access, choose "Refactor", and then "Encapsulate Field". You will be prompted for the name of the property, after which, the code for get and set will be auto generated for you.


And what if you have already been using that variable in your other classes directly? No problem - the IDE will automatically update those references to use the newly generated properties instead. Cool!