[nem-en] Initonly modifier for immutable fields

Sandro Magi smagi at springairsystems.com
Sun Jul 9 19:19:58 CEST 2006


Kamil Skalski wrote:
> - initonly field containing internally mutable value types:
> 
> The most ugly change of behaviour I observed when running and
> debugging our test suite is
> how .NET forces such code to be compiled to:
> 
> [Record]
> struct S {
>  public mutable muta : string;
> 
>  public Modify (val : string) : void
>  {
>    muta = val;
>  }
> }
> 
> [Record]
> class A {
>  public mystruct : S;
> }
> 
> def x = A (S ("first"));
> System.Console.WriteLine (x.mystruct.muta);
> x.mystruct.Modify ("second");
> System.Console.WriteLine (x.mystruct.muta);
> 
> will print:
> first
> first
> 
> Since 'mystruct' is now initonly, we can only read its *copy*, we
> cannot access a pointer (address) to it and effectively every
> operation on it is always performed on a copy not on the original
> struct.
> If you try to assign directly to muta by
> x.mystruct.muta = "second";
> 
> compiler will detect its inability to modify structure in place and
> signal error.

Are you sure this is the reason? In C# structs are always immutable, so
it seems to me that the above example should have always printed

first
first

The above example would work in C# if S were a class.

Sandro



More information about the devel-en mailing list