Possible Duplicate:
“new” keyword in property declaration
Pardon me if this is C# 101, but I am trying to understand the code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Generics
{
class RabbitCollection : ArrayList
{
public int Add(Rabbit newRabbit)
{
return base.Add(newRabbit);
}
//collections indexer
public new Rabbit this[int index]
{
get { return base[index] as Rabbit; }
set { base[index] = value; }
}
}
}
Why does the indexer have new
in front of it? By the way, Rabbit is a class defined in another file. Thanks!
Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.
An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers. An indexer can be defined the same way as property with this keyword and square brackets [] .
To declare an indexer for a class, you add a slightly different property with the this[] keyword and arguments of any type between the brackets. Properties return or set a specific data member, whereas indexers return or set a particular value from the object instance.
Try removing new from the code and you should get a warning:
RabbitCollection.this[int]' hides inherited member 'System.Collections.ArrayList.this[int]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
You may want to see new Modifier C#
The new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With