Why is new String(“Hello”) invalid in C#?

后端 未结 9 2454
太阳男子
太阳男子 2021-02-19 03:41

What is the logic/reason behind making

String s= new String(\"Hello World\");

Illegal in C#? The error is

The best over

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 04:32

    A string is immutable until you start messing with unsafe code, so the language designers chose not to add a feature that isn't needed in normal usage. That is not to say it wouldn't be handy in certain situations.

    If you do this:

    string a = "foobar";
    string b = a;
    Mutate(a, "raboof");
    Console.WriteLine("b={0}", b);
    

    where:

    unsafe void Mutate(string s, string newContents)
    {
        System.Diagnostics.Debug.Assert(newContents.Length == s.Length);
        fixed (char* ps = s)
        {
            for (int i = 0; i < newContents.Length; ++i)
            {
                ps[i] = newContents[i];
            }
        }
    }
    

    You may be surprised to know that even though string 'a' is the one that was mutated the output will be:

    b=raboof

    In this situation one would like to write:

    string a = "foobar";
    string b = new String(a);
    Mutate(a, "raboof");
    Console.WriteLine("b={0}", b);
    

    And expect to see output like:

    b=foobar

    But you can't, because it is not part of the implementation of System.String.

    And I guess a reasonable justification for that design decision is that anyone comfortable writing something like the unsafe Mutate method is also capable of implementing a method to clone a string.

提交回复
热议问题