List<T>.AddRange(T[]) adding wrong values

I have a problem with List<T>.AddRange(T[]). It happens to add the wrong values. Given a specific test, it looks like a bug. I initially thought it was about the enum of type byte, but it seems that the same happens with int, not only enums.

I solved by using Add in a loop.

I’m using the latest 3.0.2.2000.

Follows the code of the test and the relative output:

        private enum SampleEnum { Red, Green, Blue }

        protected string EnumCopySelfTest()
        {
            string log = string.Empty;
            SampleEnum expected = SampleEnum.Green;

            // AddRange from an array
            List<SampleEnum> copied = new List<SampleEnum>();
            copied.AddRange(new SampleEnum[] { SampleEnum.Green });
            log = Check(log, "AddRange(array)[0] == const", copied[0] == expected);

            // copy element by element
            SampleEnum[] array = new SampleEnum[] { SampleEnum.Green };
            List<SampleEnum> copiedByAdd = new List<SampleEnum>();
            for (int k = 0; k < array.Length; k++)
                copiedByAdd.Add(array[k]);
            log = Check(log, "Add loop[0] == const", copiedByAdd[0] == expected);

            // AddRange from a List<T>
            List<SampleEnum> source = new List<SampleEnum>();
            source.Add(SampleEnum.Green);
            List<SampleEnum> copiedFromList = new List<SampleEnum>();
            copiedFromList.AddRange(source);
            log = Check(log, "AddRange(List)[0] == const", copiedFromList[0] == expected);

            // AddRange from an int array (not an enum)
            List<int> copiedInts = new List<int>();
            copiedInts.AddRange(new int[] { 17 });
            log = Check(log, "int AddRange(array)[0] == 17", copiedInts[0] == 17);

            return log;
        }

        private static string Check(string log, string name, bool ok)
        {
            string line = (ok ? "PASS " : "FAIL ") + name;
            Trace.WriteLine("SELFTEST " + line);
            return log + line + "\r\n";
        }

Output:

SELFTEST FAIL AddRange(array)[0] == const
SELFTEST PASS Add loop[0] == const
SELFTEST PASS AddRange(List)[0] == const
SELFTEST FAIL int AddRange(array)[0] == 17

We will look into it

1 Like