Search code examples
c#generic-collections

List<T>.Capacity implementation


I am looking at the source code for List<T>. It has the property:

public int Capacity {
get {
    Contract.Ensures(Contract.Result<int>() >= 0);
    return _items.Length;
}
set {
    if (value < _size) {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
    }
    Contract.EndContractBlock();

    if (value != _items.Length) {
        if (value > 0) {
            T[] newItems = new T[value];
            if (_size > 0) {
                Array.Copy(_items, 0, newItems, 0, _size);
            }
            _items = newItems;
        }
        else {
            _items = _emptyArray;
        }
    }
}

}

What is the point to check if (value > 0) as if it is not the case this code will never be reached due to the check if (value < _size)?


Solution

  • You're forgetting about the case when value and _size are both 0. See the else block referring to an _emptyArray. This handles the case shown below.

    var list = new List<string>(16);
    Debug.Assert(list.Count == 0);
    Debug.Assert(list.Capacity == 16);
    list.Capacity = 0;