Search code examples
c#stringlanguage-lawyerfixedunsafe

Is it legal to modify strings?


Using a fixed statement one can have a pointer to a string. Using that pointer they can modify the string. But is it legally allowed in C# documentation?

using System;

class Program
{
    static void Main()
    {
        string s = "hello";
        unsafe
        {
            fixed (char* p = s)
            {
                p[1] = 'u';
            }
        }
        Console.WriteLine("hello");
        Console.Write("hello" + "\n");
        Console.ReadKey();
    }
}

// hullo
// hello

The above program modifies a string literal.


Solution

  • Per the language specification:

    Modifying objects of managed type through fixed pointers can results [sic] in undefined behavior. For example, because strings are immutable, it is the programmer's responsibility to ensure that the characters referenced by a pointer to a fixed string are not modified.

    (My emphasis)

    So, it's explicitly contemplated within the language and you're not meant to do it, but it's your responsibility, not the compiler's.