I’d like to know how set works in a property when it does more than just setting the value of a private member variable. Let’s say I’ve a private member in my class (private int myInt).
For instance, I can make sure that the the value returned is not negative
get
{
if(myInt < 0)
myInt = 0;
return myInt;
}
With SET, all I can do is affecting the private variable like so
set { myInt = value; }
I didn’t see in any book how I can do more than that. How about if I wan’t to do some operation before affecting the value to myInt? Let’s say: If the value is negative, affect 0 to myInt.
set
{
//Check if the value is non-negative, otherwise affect the 0 to myInt
}
Thanks for helping
You can do what you want.
There’s nothing to stop you having:
(or some more compact version of this)
It’s what the setters and getters were designed for.
You can add logging, debug asserts or even raise an exception if the value is out of bounds.
BUT
Users of your Setters and Getters will not expect them to do “lots” of processing or have any side effects. So they should only affect their backing variable and not go off and process 1000 text files (as an example). A connection to a database is fine, but if you’re getting a lot of data back you should replace the Get with an explicit function.
Also, take note of what @StingyJack said in his answer though.