How to translate C# 'readonly' keyword into D

Jacob Carlborg doob at me.com
Mon Feb 4 04:09:42 PST 2013


On 2013-02-04 10:02, 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();" ?

The closest would probably be defining a property with only a getter:

class Bar
{
     private IFoo foo_;

     private @property foo () { return foo_; }

     this (IFoo foo)
     {
         foo_ = foo;
     }
}

You can still change the "foo_" variable.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list