fields in @property ?

Simen kjaeraas simen.kjaras at gmail.com
Wed Jan 13 18:18:26 PST 2010


On Wed, 13 Jan 2010 08:30:39 +0100, MIURA Masahiro <echochamber at gmail.com>  
wrote:

> Hi,
>
> Is it ok to have fields in @property ?
>
> Implementing properties often require private fields to hold the
> values, and it seems natural to have them inside @property near
> the property methods.  But I couldn't find any mention in the docs
> about fields in @property.
>
> This compiles with DMD 2.039, and runs fine:
>
> ---- cut here ----
> import std.stdio;
>
> class Foo
> {
>     this(string msg) { this._msg = msg; }
>
>     @property {
> 	private string _msg; // <-- field in @property
> 	string msg() { return _msg; }
>     }
> }
>
> void main()
> {
>     auto foo = new Foo("Hello world");
>     writeln(foo.msg);
> }
> ---- cut here ----

@property {
   //stuff
}

means that anything within the curly braces has the @property attribute.  
For fields, @property does nothing, so

class foo {
   @property {
     int bar;
     int baz( ) { return bar; };
   }
}

is equivalent to

class foo {
   int bar;
   @property {
     int baz( ) { return bar; }
   }
}

In other words, this is not (or at least should not be) possible:

class foo {
   @property {
     int bar;
     int baz( ) { return bar; };
   }
   @property {
     int bar; // Duplicate foo.bar.
     int qux( ) { return bar; } // Will not return the latter bar.
   }
}

-- 
Simen


More information about the Digitalmars-d-learn mailing list