Read-only property without @property

Cliff via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 26 15:58:51 PDT 2014


On Friday, 26 September 2014 at 19:47:15 UTC, Steven 
Schveighoffer wrote:
> I wanted to bring this over from D.learn, because I've never 
> seen this before, and it's an interesting solution to creating 
> a property without much boilerplate.
>
> So here it is:
>
> class Foo
> {
>    union
>    {
>       private int _a; // accessible only in this module
>       public const int a; // accessible from anywhere, but read 
> only
>    }
> }
>
> And it works now, probably has for a while.
>
> Thoughts? This can easily be boilerplated in something like 
> roprop!(int, "a")
>
> I am really not sure what union does to compiler optimization 
> or runtime concerns, if it has any significant drawbacks. From 
> what I can tell, it's a valid solution.
>
> Credit to Mark Schütz for the idea.
>
> -Steve

This is a clever syntax, but I can't say I particularly care for 
it since it aliases two names for the same location which differ 
only in their visibility, and this feels... wrong to me somehow.

In C# this is a sufficiently common practice that the property 
syntax allows for it directly:

class Foo
{
     int A { get; private set; }
}

The compiler automatically creates a (hidden) backing property 
(this is an implementation detail of course), both internal and 
external customers use the same name, and there is no redundancy. 
  If I were to compare the D way and the C# way, I would prefer to 
C# way for this trivial-property case.  What I would NOT want is 
C#'s special handling of properties to go along with it - a D 
analog would preserve A's access methods and handling as if it 
were a field if that was the user's wish.

That's my $0.02.


More information about the Digitalmars-d mailing list