Can I make a variable public and readonly (outside where was declared) at same time?

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 26 10:36:48 PDT 2014


On Friday, 26 September 2014 at 17:16:04 UTC, AsmMan wrote:
> I know I can combine it by making an extra variable plus a 
> property like this:
>
> class Foo
> {
>   private int a_;
>
>   void do_something1()
>   {
>     a_ = baa();
>   }
>
>   void do_something2()
>   {
>     if(cond) a_ = baa2();
>   }
>
>   @property int a()
>   {
>       return a;
>    }
> }
>
> This is the C#'s to do which I'm translated to D within my 
> limited knowledge. I don't do much OOP, maybe it's possible and 
> I don't know. I'm using @property to make 'a' accessible and 
> readonly at same time but I wanted to do that without this a_ 
> extra variable, i.e, only the methods within the Foo class can 
> assign a new value to a but a instance of Foo can't. An 
> imaginary code example:
>
> class Foo
> {
>   public MAGIC_HERE int a;
>
>   void do_something1()
>   {
>     a = baa();
>   }
>
>   void do_something2()
>   {
>     if(cond) a = baa2();
>   }
> }
>
>
> And then:
>
> Foo f = new Foo();
> writeln(f.a); // output value of a
> f.a = 10; // compile error: a is readonly outside Foo's methods.
>
> I hope it's clear (sorry for por English)

The closest you can get is probably this:

     class Foo {
         private int a_;

         @property int a() {
             return a_;
         }

         private @property void a(int value) {
             a_ = value;
         }
     }

You can then assign to `a` inside the class `Foo` _and_ inside 
its module (because `private` is always accessible from within 
the same module), while from other modules, it can only be read.

But it's not exactly a read-only variable, because you cannot 
take an address from it, for example.

Alternatively, you could create a union with a private and a 
public member with the same types, but I wouldn't recommend it. 
Besides, the members would need to have different names:

     class Foo {
         union {
             private int a;
             public int b;
         }
     }


More information about the Digitalmars-d-learn mailing list