In my last c# interview,
I was asked to prove immutability of C# string,I know what is meant by immutability of c# string,But is it possible to prove immutability of c# str
I can prove that a string
is not immutable. All I need to do is to show some code which mutates a string
, like so:
using System;
using System.Runtime.InteropServices;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
const string test = "ABCDEF"; // Strings are immutable, right?
char[] chars = new StringToChar {str = test}.chr;
chars[0] = 'X';
// On an x32 release or debug build or on an x64 debug build,
// the following prints "XBCDEF".
// On an x64 release build, it prints "ABXDEF".
// In both cases, we have changed the contents of 'test' without using
// any 'unsafe' code...
Console.WriteLine(test);
// The following line is even more disturbing, since the constant
// string "ABCDEF" has been mutated too (because the interned 'constant' string was mutated).
Console.WriteLine("ABCDEF");
}
}
[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
[FieldOffset(0)] public string str;
[FieldOffset(0)] public char[] chr;
}
}
Now whether this should be considered a bug in C# is a different matter. :)
(The answer is probably that FieldOffset
should be considered to be unsafe
- the code above is purportedly safe
and therefore the string
should not be mutatable.)
Also, I think you could legitimately argue that string
is immutable in spirit, even if there are silly edge cases which violate its immutability in supposedly safe code.