C Board  

Go Back   C Board > General Programming Boards > C# Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 10-10-2005, 03:40 PM   #1
Registered User
 
Join Date: Sep 2005
Posts: 16
Private or Public

Hi, I was curious why you would neet to declare and variable in a class as private, and then use the get and set for the property, when you could just use a public variable? I might be getting something confused and need just a bit more explanation.

Thanks
gtriarhos is offline   Reply With Quote
Old 10-10-2005, 04:28 PM   #2
& the hat of GPL slaying
 
Thantos's Avatar
 
Join Date: Sep 2001
Posts: 5,732
You can do it to maintain a proper state of the object.

Lets say you had an object that contained two integers. One of which can never be lower then 2. Well if you just had a public variable then anyone could assign a value of 1 to it. However if you make them go through one of your functions to change it then you can check first to make sure its a proper value.
Thantos is offline   Reply With Quote
Old 10-10-2005, 04:32 PM   #3
Registered User
 
Frobozz's Avatar
 
Join Date: Dec 2002
Posts: 546
Concerning what Thantos said, it also makes it so the programmer using your object does not have to check to see if the value going into it is less than 2. This makes it easier on the programmer later when he has to debug the program.
Frobozz is offline   Reply With Quote
Old 10-10-2005, 07:14 PM   #4
Banned
 
nickname_changed's Avatar
 
Join Date: Feb 2003
Location: Australia
Posts: 986
And even if you don't want to check if it's less than two, it's best to do it anyway, because one day you might like to. For example, in all of my properties that return a string, I check if the string is null and return string.Empty rather than null.

It's just good practice. One of the great goals of object oriented programming is encapsulation. Exposing your private parts to strangers isn't recommended
nickname_changed is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
OOP Question DB Access Wrapper Classes digioz C# Programming 2 09-07-2008 04:30 PM
Linking problems in Visual Studio h3ro C++ Programming 5 03-04-2008 02:39 PM
Need help with calculator program Kate C# Programming 1 01-16-2004 10:48 AM
I need a code for Tic Tac Toe game ? martyr C++ Programming 11 12-07-2003 03:29 AM
structure vs class sana C++ Programming 13 12-02-2002 07:18 AM


All times are GMT -6. The time now is 09:22 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22