Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Very odd, but it works
void Main()
{
var f = new Foo ();
f.Inc ();
f.Inc ();
f.X.Dump ();
}
struct Foo {
public readonly int X;
public Foo (int x) { X = x; }
public void Inc () {
this = new Foo (X + 1);
}
}
readonly Foo f = new Foo ();
void Main()
{
// Inc cannot reassign f since its readonly
// the assignment is silently ignored. The same
// behaviour can be observed when manually trying
// to change a readonly field using IL.
f.Inc ();
f.Inc ();
f.X.Dump ();
}
struct Foo {
public readonly int X;
public Foo (int x) { X = x; }
public void Inc () {
this = new Foo (X + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment