Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
Collection<T> RemoveAt vs RemoveItem

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda