On Monday, 29 June 2015 at 20:12:12 UTC, Assembly wrote:
I believe it's a design choice, if so, could someone explain why? is immutable better than C#'s readonly so that the readonly keyword isn't even needed? for example, I'd like to declare a member as readonly but I can't do it directly because immutable create a new type (since it's a type specific, correct?) isn't really the same thing.

MyClass x = new MyClass();

if I do

auto x = new immutable(MyClass)();

give errors

There are a few ways you can enforce a field to be readonly.

You can use properties:

import std.stdio;

class Foo
{
        private int _bar;
        
        this(int bar)
        {
                this._bar = bar;
        }

        public @property int bar()
        {
                return this._bar;
        }
}

void main(string[] args)
{
        auto foo = new Foo(1337);

        writefln("%s", foo.bar);

        // Error:
        // foo.bar = 10;
}

or a manifest constant:

import std.stdio;

class Foo
{
        public enum int bar = 1337;
}

void main(string[] args)
{
        auto foo = new Foo();

        writefln("%s", foo.bar);

        // Error:
        // foo.bar = 10;
}

Reply via email to