Refactoring – a new feature in the Visual C# 2.0 IDE
CoderSource.net
Refactoring – a new feature in the Visual C# 2.0 IDE - Article by muskad202
Level: BeginnerType: Article
Rating: Page: 2 of 4

Date: 4/23/2006 12:00:00 AM

Environment: Windows, Visual Studio .Net 2005

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!

1 2 3 4

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us