How does appending to a null string work in C#?

后端 未结 4 495
陌清茗
陌清茗 2021-02-05 00:02

I was surprised to see an example of a string being initialised to null and then having something appended to it in a production environment. It just smelt wrong.

I was

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 00:20

    the + operator for strings are just shorthand for string.Concat which simply turns null arguments into empty strings before the concatenation.

    Update:

    The generalized version of string.Concat:

    public static string Concat(params string[] values)
    {
        int num = 0;
        if (values == null)
        {
            throw new ArgumentNullException("values");
        }
        string[] array = new string[values.Length];
        for (int i = 0; i < values.Length; i++)
        {
            string text = values[i];
            array[i] = ((text == null) ? string.Empty : text);
            num += array[i].Length;
            if (num < 0)
            {
                throw new OutOfMemoryException();
            }
        }
        return string.ConcatArray(array, num);
    }
    

提交回复
热议问题