Prev: Getting Focus on outside application child windows
Next: What is the point to use List when InnerList gives more in CollectionBaseclass
From: Peter Duniho on 12 Feb 2010 12:45 Tony Johansson wrote: > [...] > I can use the original way to write key and value and be happy with that but > I want to understand why I can't use the foreach because the baseclass > NameObjectCollectionBase do supply one which I have hopped to use in my > derived class MyCollection but it doesnt't work because the element that I > think is a DictioneryEntry is string so that give runtime error. > I have also tried to use this way but this will only write the value. I have > hopped that this current here would have been > a DictionaryEntry but it's a string. > IEnumerator e = myCol.GetEnumerator(); > while (e.MoveNext()) > Console.WriteLine(e.Current); > > So can somebody explain why it's not possible to a foreach when the > baseclass have one that that derived class can inherit and use ?? You've already answered the question. It's because the enumerator for NameObjectCollectionBase doesn't enumerate key/value pairs, but rather just the keys. This is documented: http://msdn.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.getenumerator.aspx NameObjectCollectionBase doesn't implement any dictionary interface that would allow paired enumeration. If you want to retrieve keys and values in pairs, you can: � Use the indexer as you've shown in your own code � Enumerate the keys, and use the BaseGet(String) method overload to get each value for each key � Call the BaseGetAllKeys() and BaseGetAllValues() methods to get a pair of arrays you can enumerate in parallel Pete |