readonly member (but assignable at constructor time)

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Apr 27 03:43:53 UTC 2018


On Friday, April 27, 2018 02:59:16 Dr.No via Digitalmars-d-learn wrote:
> In C# you can have a readonly member assignable either at
> declaration or constructor time, like this:
>
> class C
> {
>    readonly myClass mc;
>
>    this()
>    {
>      mc = new myClass();
>    }
>
>
>    void doSomething()
>    {
>      mc = new myClass(); // wrong! result in compiler error, mc is
> readonly
>    }
> }
>
> Does D have something like this natively or there's a way to do
> so with traits/CTFE at runtime?

D has const, though that has some pretty far-reaching repercussions, since
it means that the object can't be mutated at all, and the only member
functions that can be called on it are const or inout.

If you want to specifically make it so that the object is mutable but the
reference can't be assigned to, then it would have to be protected by a
wrapper struct that @disabled opAssign and then either used alias this or
opDispatch to forward calls to the class reference inside the struct. D's
const is transitive and does not have any form of head-const, so const can't
be used in a case like that.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list