Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code have new in the collections indexer [duplicate]

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!

like image 428
Irfarino Avatar asked Jul 27 '12 03:07

Irfarino


People also ask

Why do we use indexers in C#?

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.

What defines a collection that can be accessed via an indexer?

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 [] .

What statement do you use to implement an indexer?

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.


1 Answers

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.

like image 170
Habib Avatar answered Nov 14 '22 23:11

Habib