I have a class that inherits from Dictionary<string, string>. Within an instance method, I want to iterate over all KeyValuePair<string, string>‘s. I’ve tried doing the following:
foreach (KeyValuePair<string, string> pair in base)
But this fails with the following error:
Use of keyword ‘base’ is not valid in this context
How can I iterate over the KeyValuePair<string, string>‘s in an instance method in a class that derives from Dictionary<string, string>?
Edit: I found I can do the following:
var enumerator = base.GetEnumerator();
while (enumerator.MoveNext())
{
KeyValuePair<string, string> pair = enumerator.Current;
}
However, I would still like to know if there’s a way to do this via a foreach loop.
Edit: thanks for the advice about not inheriting from Dictionary<string, string>. I’m instead implementing System.Collections.IEnumerable, ICollection<KeyValuePair<string, string>>, IEnumerable<KeyValuePair<string, string>>, IDictionary<string, string>.
First, deriving from the .NET collection classes is generally ill-advised because they don’t offer virtual methods for calls not inherited from
object. This can result in bugs when passing your derived collection in via a base-class reference somewhere. You are better off implementing theIDictionary<T,TKey>interface and aggregating aDictionary<,>inside your implementation – to which you then forward the appropriate calls.That aside, in your specific case, what you want to do is:
The
basekeyword is primarily used to access specific members of your base class. That’s not what you’re doing here – you are attempting to iterate over the items of a particular instance … which is simply thethisreference.