Can ToArray() throw an exception?

前端 未结 5 1506
不知归路
不知归路 2020-12-31 13:54

While the answer to this question is excellent, it implies that you should surround calls to List.ToArray() in a lock for concurrency. this blog post also implies that it c

5条回答
  •  一整个雨季
    2020-12-31 13:59

    You will not find documentation about possible exceptions of ToArray method for one simple reason. This is an extension method that has many 'overloads'. They all have same method signature, but implementation is different for different collection types, e.g. List and HashSet.

    However, we can make a safe assumption for most of the code that .NET framework BCL does not perform any locking for performance reasons. I've also checked very specifically implementation of ToList for List.

    public T[] ToArray()
    {
        T[] array = new T[this._size];
        Array.Copy(this._items, 0, array, 0, this._size);
        return array;
    }
    

    As you might have imagined, it's quite simple code which ends up executing in mscorlib. For this specific implementation, you can also see exceptions which could occur in MSDN page for Array.Copy method. It boils down to an exception which is thrown if rank of the list changes right after destination array was just allocated.

    Having in mind that List is trivial example, you can imagine that chances for exception rise on structures which require more complicated code in order to store in an array. Implementation for Queue is a candidate which is more likely to fail:

    public T[] ToArray()
    {
        T[] array = new T[this._size];
        if (this._size == 0)
        {
            return array;
        }
        if (this._head < this._tail)
        {
            Array.Copy(this._array, this._head, array, 0, this._size);
        }
        else
        {
            Array.Copy(this._array, this._head, array, 0, this._array.Length - this._head);
            Array.Copy(this._array, 0, array, this._array.Length - this._head, this._tail);
        }
        return array;
    }
    

提交回复
热议问题