[nem-en] Initonly modifier for immutable fields
Kamil Skalski
kamil.skalski at gmail.com
Sun Jul 9 19:28:33 CEST 2006
Try this program with and without 'readonly' modifier:
struct S {
public string y;
public S (string a, string b) {
y = b;
}
public void Modify (string i) {
y = i;
}
}
class A {
public /*readonly*/ S z;
public A(S a) {
z = a;
}
}
class M {
public static void Main(string[] args) {
A x = new A (new S ("b"));
System.Console.WriteLine (x.z.y);
x.z.Modify ("aaaaaaaaa");
System.Console.WriteLine (x.z.y);
}
}
The outputs can be quite suprising for anyone ;)
On 7/9/06, Sandro Magi <smagi at springairsystems.com> wrote:
> 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
>
> _______________________________________________
> https://nemerle.org/mailman/listinfo/devel-en
>
--
Kamil Skalski
http://nazgul.omega.pl
More information about the devel-en
mailing list