2

I have used collection initializer for a Dictionary and received a TypeInitializationException:

public static Dictionary<Environment.SpecialFolder, string> specialFolders = new Dictionary<Environment.SpecialFolder, string>
{
    // ...
    {Environment.SpecialFolder.MyDocuments, "abc"},
    // ...
    {Environment.SpecialFolder.Personal   , "def"},
    // ...
};

As there is no useful info like InnerException, call stack or whatever else it is confusing. So I investigated the problem a bit and realized that there are two keys having the same value.

Regarding the IL, this collection initializer syntax is converted to Dictionary.Add(...) calls and as such calling Add two times with the same key raises System.ArgumentException (which is the inner exception I would expect in the TypeInitializationException). So I effectivelly answered my original question, but another one has emerged:

Why the class has to implement IEnumerable (and thus provide IEnumerator) - which is intended to read the collection, not to write it - when finally the collection initializer is converted to Add call (which is not guaranteed to be present in the class via the IEnumerable)? Am I missing something important?

sharpener
  • 1,383
  • 11
  • 22
  • FYI, both special-folder enums have the same values(`Personal = 5`, `MyDocuments = 5`) and [`Enum.Equals`](http://msdn.microsoft.com/en-us/library/8bafh2by(v=vs.110).aspx) checks if the value of two instances is equal. So this enum is is really a bad candidate for a dictionary-key. – Tim Schmelter Sep 30 '14 at 08:43
  • Interesting question, I would have expected it to require something like `IList`, which would provide the `Add` and as a side effect, the `IEnumerable` interface - but that's not the case. – C.Evenhuis Sep 30 '14 at 08:44
  • Dereferencing one of the answers of the mentioned question I'm duplicating - the very detailed discussion is here: http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx – sharpener Sep 30 '14 at 09:06

0 Answers0