You'll always find some tricky situations where the new
keyword can be used for hiding while it can be avoided most of the times.
However, recently I really needed this keyword, mainly because the language lacks some other proper synthax features to complete an existing accessor for instance:
If you consider an old-fashioned class like:
KeyedCollection<TKey, TItem>
You will notice that the accesor for acessing the items trough index is:
TItem this[Int32 index] { get; set; }
Has both { get; set; }
and they are of course mandatory due to the inheritance regarding ICollection<T>
and Collection<T>
, but there is only one { get; }
for acessing the items through their keys (I have some guesses about this design and there is plenty of reasons for that, so please note that I picked up the KeyedCollection<TKey, TItem>)
just for illustrations purposes).
Anyway so there is only one getter for the keys access:
TItem this[TKey key] { get; }
But what about if I want to add the { set; }
support, technically speaking it's not that stupid especially if you keep reasoning from the former definition of the propery, it's just a method... the only way is to implement explicitly another dummy interface but when you want to make implicit you have to come up with the new
keyword, I'm hiding the accessor definition, keeping the get; base definition and just add a set stuffed with some personal things to make it work.
I think for this very specific scenario, this keyword is perfecly applicable, in particular in regards to a context where there is no brought to the { get; }
part.
public new TItem this[TKey key]
{
get { return base... }
set { ... }
}
That's pretty much the only trick to avoid this sort of warning cause the compiler is suggesting you that you're maybe hiding without realizing what you are doing.