-
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
-
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.
-
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. ;)
-
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 ;)