How to translate C# 'readonly' keyword into D

simendsjo simendsjo at gmail.com
Mon Feb 4 02:30:49 PST 2013


On Monday, 4 February 2013 at 10:26:55 UTC, simendsjo wrote:
> On Monday, 4 February 2013 at 09:02:31 UTC, o3o wrote:
>> I'm a C# programmer, when I apply IoC pattern  I use 
>> "readonly" keyword 
>> (http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.71%29.aspx) 
>> in this manner:
>>
>> :// C# code
>> :interface IFoo {
>> :  void Fun();
>> :}
>> :
>> :class Foo: IFoo {
>> :  void Fun() {...}
>> :}
>> :class Bar {
>> :  private readonly IFoo foo;
>> :  // inject IFoo into Bar
>> :  Bar(IFoo foo) {
>> :    // assert(foo != null);
>> :    this.foo = foo;
>> :  }
>> :  void Gun() {
>> :    // foo = new Foo(); //// ERROR: foo is readonly!
>> :    foo.Fun();
>> :  }
>> :}
>>
>> Can someone help me to translate "readonly IFoo foo;" so that 
>> the dmd compiler raises an error when I write "foo = new 
>> Foo();" ?
>>
>> I try:
>> :// D code
>> :interface IFoo {
>> :   void fun();
>> :}
>> :
>> :class Foo: IFoo {
>> :   void fun() {
>> :      writeln("fun...");
>> :   }
>> :}
>> :
>> :class Bar {
>> :   private const IFoo service;
>> :   this(const IFoo service) {
>> :      this.service = service;
>> :   }
>> :
>> :   void gun() {
>> :      service.fun();
>> :   }
>> :}
>> :unittest {
>> :  const(IFoo) s = new Foo;
>> :  auto bar = new Bar(s);
>> :  bar.gun();
>> :}
>> but the compiler complains:
>> Error: function main.IFoo.fun () is not callable using 
>> argument types () const
>
> In D, everything accessible from const is also const. You 
> specifically state that you will not modify your IFoo instance. 
> But then you call foo(). foo() in turn isn't marked as const, 
> so this can modify IFoo, and thus break const.
> So.. Every method you call through a const instance must also 
> be const, otherwise you have the ability to change something 
> that should be a constant.

So this works:
interface IFoo {
     void fun() const;
}

class Foo : IFoo {
     void fun() const {}
}

class Bar {
     private const IFoo service;
     this(const IFoo service) {
         this.service = service;
     }

     void gun() {
         service.fun();
     }
}

unittest {
     const s = new Foo();
     auto bar = new Bar(s);
     bar.gun();
}

void main() {}


More information about the Digitalmars-d-learn mailing list