Why is this code new in the collection indexer

Possible duplicate:
"new" keyword in property declaration

Excuse me if this is C # 101, but I'm 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!

+6
source share
4 answers

Try removing the new one from the code and you should get a warning:

RabbitCollection.this [int] ' hides the inherited element ' System.Collections.ArrayList.this [Int]. To make the current member override this implementation, add an override keyword. Otherwise, add a new keyword.

You might want to see the new C # modifier

The new keyword explicitly hides the element inherited from the base class . When you hide an inherited element, the derived version of the member replaces the version of the base class. Although you can hide participants without using a new modifier, the result is a warning. If you use new ones to explicitly hide the participant, it suppresses this warning and documents the fact that the derived version is intended to be replaced.

+6
source

Since the base class ( ArrayList ) also has an index. new says: "I intentionally replace a member of the base class with one of mine."

It also works without new , but new tells the compiler that you know what you are doing.

Of course, in code written at any time over the last seven or eight years, you should use List<T> instead of ArrayList , and then you do not need to create a child with its own strong type index.

+4
source

This is because this class hides a member of the base class (ArrayList also defines the same index).

New Tells the compiler that this behavior is intended, and not by mistake.

Read the C # polymorphism guide

Replacing an element of a base class with a new derived element requires a new keyword. If the base class defines a method, field, or property, a new keyword is used to create a new definition for that method, field, or property of the derived class. A new keyword is placed before the return type of the member of the class that is being replaced.

+4
source

Usually, if the base type involves overriding the method, it will be marked as virtual. In this case, the subtype simply marks the method with overriding.

If the base type does not exist, and the subtype defines an identical method, ambiguity arises. The C # compiler asks you to confirm that you want this by marking the subtype method as new - essentially saying, β€œyes, I know, and I want to hide the method suggested by the base type”

+1
source

Source: https://habr.com/ru/post/921447/


All Articles