Home > front end >  Collection<T> RemoveAt vs RemoveItem
Collection<T> RemoveAt vs RemoveItem

Time:01-19

Collection.RemoveAt(Int32) Method vs Collection.RemoveItem(Int32)

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.removeat?view=net-6.0

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.removeitem?view=net-6.0

What is the difference between these two methods? According to the docs RemoveItem is virtual and RemoveAt is not, and that is the only difference I can find.

The excerpted source code looks something like this

    IList<T> items;

    ....

    public void RemoveAt(int index) {
        if( items.IsReadOnly) {
            ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
        }

        if (index < 0 || index >= items.Count) {
            ThrowHelper.ThrowArgumentOutOfRangeException();
        }

        RemoveItem(index);
    }

    ...

    protected virtual void RemoveItem(int index) {
        items.RemoveAt(index);
    }

https://github.com/microsoft/referencesource/blob/master/mscorlib/system/collections/objectmodel/collection.cs

So my question more properly is why are there two very similar methods differing only by being virtual or not? What is the use case? Is this just historical cruft? What's the story?

CodePudding user response:

Reason for having two methods is to allow consumer to create subclass of Collection<T> that will override behavior of inserting\removing items. You can override InsertItem, RemoveItem, SetItem, ClearItems.

For example, you can override this methods in subclass to send events (like ObservableCollection) or to log any collection change.

CodePudding user response:

The documentation for RemoveAt includes this interesting note at the bottom of the page:

Derived classes can override RemoveItem(Int32) to change the behavior of this method.

The ultimate conclusion is that RemoveAt calls RemoveItem, and that derived classes override the behavior by overriding RemoveItem.

  •  Tags:  
  • Related