www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why D doesn't have an equivalent to C#'s readonly?

reply "Assembly" <jckj33 gmail.com> writes:
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
next sibling parent "Gary Willoughby" <dev nomad.so> writes:
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
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; }
Jun 29 2015
prev sibling parent reply "sigod" <sigod.mail gmail.com> writes:
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
parent reply "anonymous" <anonymous example.com> writes:
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
parent "sigod" <sigod.mail gmail.com> writes:
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.
Jun 29 2015