OK, that is nasty... the dangers of using a union. That may work, but isn't a very good idea - I guess I'd compare it to reflection (where you can do most things). I'd be interested to see if this works in a constrained access environment - if so, it may represent a bigger problem...
I've just tested it without the "Full Trust" flag, and the runtime rejects it:
Could not load type 'MemoryAccess'
from assembly 'ConsoleApplication4,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' because objects
overlapped at offset 0 and the
assembly must be verifiable.
And to have this flag, you already need high trust - so you can already do more nasty things. Strings are a slightly different case, because they aren't normal .NET objects - but there are other examples of ways to mutate them - the "union" approach is an interesting one, though. For another hacky way (with enough trust):
string orig = "abc ", copy = orig;
typeof(string).GetMethod("AppendInPlace",
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(string), typeof(int) }, null)
.Invoke(orig, new object[] { "def", 3 });
Console.WriteLine(copy); // note we didn't touch "copy", so we have
// mutated the same reference
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…