digitalmars.D.learn - Why D doesn't have an equivalent to C#'s readonly?
- Assembly (10/10) Jun 29 2015 I believe it's a design choice, if so, could someone explain why?
- Gary Willoughby (37/47) Jun 29 2015 There are a few ways you can enforce a field to be readonly.
- sigod (6/16) Jun 29 2015 Why? I think `const` and `immutable` even better than C#'s
I believe it's a design choice, if so, could someone explain why? 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
Jun 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 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 errorsThere 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; }
Jun 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 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`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();`.
Jun 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.
Jun 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:Yes, you're right. It seems I've mistyped `immutable` when was checking it with compiler.`new immutable(MyClass)()` is invalid code.It's perfectly fine, actually.
Jun 29 2015