The code below seemingly results in a System.TypeInitializationException whenever anything in the Define class is called. The pairs are guaranteed to be different as shown below, and no code modifies the dictionary in any way. Yet the error ArgumentException: An item with the same key has already been added. Key: Key1 is thrown without fail every time. Is there any reason this happens?
public static class Define
{
public static readonly Dictionary<DefineChoices, string> Definitions = new([Pair1, Pair2]);
public enum DefineChoices
{
Key1,
Key2
}
public static readonly KeyValuePair<DefineChoices, string> Pair1 = new(DefineChoices.Key1, "string1");
public static readonly KeyValuePair<DefineChoices, string> Pair2 = new(DefineChoices.Key2, "string2");
Stack trace below:
Unhandled exception. System.TypeInitializationException: The type initializer for 'Program.Namespace.Define' threw an exception.
---> System.ArgumentException: An item with the same key has already been added. Key: Key1
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at System.Collections.Generic.Dictionary`2.AddRange(IEnumerable`1 enumerable)
at System.Collections.Generic.Dictionary`2..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Collections.Generic.Dictionary`2..ctor(IEnumerable`1 collection)
at Program.Namespace.Define..cctor() in FilePath\Define.cs:line 2
--- End of inner exception stack trace ---
>Solution :
The initialization order is significant while initializing static fields. So if you arrange your class like the below it will work :
public static class Define
{
public static readonly KeyValuePair<DefineChoices, string> Pair1 = new(DefineChoices.Key1, "string1");
public static readonly KeyValuePair<DefineChoices, string> Pair2 = new(DefineChoices.Key2, "string2");
public static readonly Dictionary<DefineChoices, string> Definitions = new([Pair1, Pair2]);
public enum DefineChoices
{
Key1,
Key2
}
}
The question of why you are getting a duplicate key of Key1 is because it has the default uninitialized value of integer which is 0. Even if your enum would start with 1 as the start value you would get a duplicate key value of 0.