Why do I need "new" when implementing CollectionBase.RemoveAt()???

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I've implemented a number of strongly-typed collections that inherit from
CollectionBase and recently noticed something that I don't fully understand.

CollectionBase defines method RemoveAt(). However, CollectionBase
implements IList which also defines method RemoveAt(). In my collection when
I code my own RemoveAt() method, the compiler issued a warning indicating
that my RemoveAt() must be defined with a "new" keyword. So, to keep the
compiler happy, I added the new keyword as follows:

new public virtual void RemoveAt( int idx )
{
List.RemoveAt( idx );
}

I'm guessing that this invokes the IList.RemoveAt() method since I'm
explicitly indicating List.RemoveAt(). If I code it as follows, I assume it
invokes the CollectionBase.RemoveAt() method:

new public virtual void RemoveAt( int idx )
{
RemoveAt( idx );
}

The new keyword as a modifier hides the base classe's implementation but
don't these two methods do the same thing? Why does CollectionBase's
implementation of RemoveAt() hide the IList implementation? Why doesn't it
just use IList's? Or am I missing something else??? :)

..ARN.
 
alanrn said:
I've implemented a number of strongly-typed collections that inherit from
CollectionBase and recently noticed something that I don't fully understand.

CollectionBase defines method RemoveAt(). However, CollectionBase
implements IList which also defines method RemoveAt(). In my collection when
I code my own RemoveAt() method, the compiler issued a warning indicating
that my RemoveAt() must be defined with a "new" keyword. So, to keep the
compiler happy, I added the new keyword as follows:

<snip>

This is because RemoveAt isn't a virtual method. That means that if
anyone has a reference to your collection just as a CollectionBase and
calls RemoveAt, it won't call your method - it will call
CollectionBase's implementation.
new public virtual void RemoveAt( int idx )
{
List.RemoveAt( idx );
}

I'm guessing that this invokes the IList.RemoveAt() method since I'm
explicitly indicating List.RemoveAt().

No, that's calling RemoveAt on the IList which the List property
returns - that's not the same as calling:

((IList)this).RemoveAt(idx)
 
Back
Top