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?