Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"An item of the same key has already been added" despite the keys being guaranteed different

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 ---

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading