Thread overview
Why D doesn't have an equivalent to C#'s readonly?
Jun 29, 2015
Assembly
Jun 29, 2015
Gary Willoughby
Jun 29, 2015
sigod
Jun 29, 2015
anonymous
Jun 29, 2015
sigod
June 29, 2015
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
June 29, 2015
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;
}
June 29, 2015
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

Why? I think `const` and `immutable` even better than C#'s `readonly`. Also, are you aware that it's recommended to use `const` instead of `readonly`?

`new immutable(MyClass)()` is invalid code. Try `immutable MyClass x = new MyClass();`.
June 29, 2015
On Monday, 29 June 2015 at 22:11:16 UTC, sigod wrote:
> `new immutable(MyClass)()` is invalid code.

It's perfectly fine, actually.

June 29, 2015
On Monday, 29 June 2015 at 22:22:46 UTC, anonymous wrote:
> On Monday, 29 June 2015 at 22:11:16 UTC, sigod wrote:
>> `new immutable(MyClass)()` is invalid code.
>
> It's perfectly fine, actually.

Yes, you're right. It seems I've mistyped `immutable` when was checking it with compiler.