post/pre-increment/decrement and property

Robert Clipsham robert at octarineparrot.com
Tue Feb 7 14:54:53 PST 2012


On 07/02/2012 22:37, Vidar Wahlberg wrote:
> Take the following code:
> int _foo;
> @property auto foo() {
> return _foo;
> }
> @property auto foo(int foo) {
> return _foo = foo;
> }
> void main() {
> ++foo;
> }
>
>
> This won't compile, and it sort of makes sense (at least to me), but is
> it (or will it in the future be) possible to achieve this in some way?
>
> I like to encapsulate class/struct members this way so I can easily add
> validation of the value in the setter at a later time (granted, I can
> add getter/setter properties when it turns out that I do need to
> validate the values, but that's beside the point).

Try this:
----
int _foo;
@property ref foo() {
         return _foo;
}
@property ref foo(int foo) {
         return _foo = foo;
}
void main() {
         ++foo;
}
----

Using 'ref' instead of auto returns a reference to _foo, allowing it to 
be modified.

-- 
Robert
http://octarineparrot.com/


More information about the Digitalmars-d-learn mailing list