'Why index and size are casted to uint in System.Collections.Generic.List.Insert method?

The code is taken from here https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Collections/Generic/List.cs

The question is about this particular line:

if ((uint)index > (uint)_size)

Whole method:

// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item)
{
    // Note that insertions at the end are legal.
    if ((uint)index > (uint)_size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
    }
    if (_size == _items.Length) EnsureCapacity(_size + 1);
    if (index < _size)
    {
        Array.Copy(_items, index, _items, index + 1, _size - index);
    }
    _items[index] = item;
    _size++;
    _version++;
}


Solution 1:[1]

I would call it a smart (little) trick, a micro-optimization.

Note that there are 2 conditions to check for OutOfRange:

  1. index > size
  2. index < 0

By casting to uint (a no-op in hardware) you get away with one comparison instead of two. All negative int values will be cast to an uint that is > int.MaxValue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1