Can I make a variable public and readonly (outside where was declared) at same time?
    Gary Willoughby via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Fri Sep 26 10:28:22 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)
I think the extra variable and the properties are the way to go 
and it's the idiomatic way. In fact that's the reason properties 
are there.
Saying that though, you can achieve what you want implementing a 
little more code using opDispatch. opDispatch intercepts calls to 
undefined members and deals with them, in this case forwarding to 
a private variable.
http://dlang.org/operatoroverloading.html#dispatch
    
    
More information about the Digitalmars-d-learn
mailing list