Shadowing
Suppose we have this base class
public class BaseClass
{
public string Name { get; set; }
}
Now suppose we derive from it and for some reason, we want to have a name property that behaves differently:
public class DerivedClass
{
public string Name
{
get { return "Always the same"; }
set { throw new Exception(); }
}
}
The C# compiler will complain that we cannot do this, the class already has a Name
property! What we can do, is tell the C# compiler that when we're using DerivedClass
we want to use our Name
property. We do this by adding the new
property to the Name
property in DerivedClass
:
public new string Name
This is called shadowing
Side-Effects
When you use DerivedClass
as a type of DerivedClass
everything behaves as you'd expected it:
DerivedClass derived = new DerivedClass();
derived.Name = "Joe"; // Exception
But if you attempt to use Name
by using the base class, you're really using the BaseClass
implementation:
BaseClass base = derived;
base.Name = "Joe"; // No Exception
There is no way to prevent this.
Back to the Question
When using generics, you don't mark the indexer as new
because it's not always a new
method (it is only when TKey is a string
), but when it needs to be, it is implicitly new
. Thus, in those cases, the C# compiler will use the version of the method/indexer that that it knows about.
In the case of using it as a StringDictionary<string>
, it'll use your custom implementation. It the case of using it as a Dictionary<string, string>
, it'll use the Dictionary<string,string>
implementation of the indexer.