Mwigs
Mwigs

Reputation: 231

Adding array to list overwrites previous elements

I am trying to create a simple color gradient bitmap by iterating through all possible color combinations and adding each value to a list. Each individual RGB value is stored as an int array in the main list.

Problems occur for me when I am trying to add the array to my list. It overwrites all previous entries in the list, at last I end up with a list full of color arrays, all filled with the values 255. I know there must exist a better way to create a color spectrum bitmap than this rather clunky way, but I am very interested in why it behaves like this.

int[] temp = new int[3];
for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            temp[0] = r;
            temp[1] = g;
            temp[2] = b;
            colors.Add(temp);
        }
    }
}

Upvotes: 0

Views: 890

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

User NikhilAgrawal's answer is correct, I'd recommend you to use the dedicated Color struct in System.Drawing namespace. As the result you get many useful methods and operators for free.

The your code becomes:

List<Color> colors = new List<Color>();
for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            colors.Add(Color.FromArgb(r,g,b));
        }
    }
}

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

You problem is that temp is an array and arrays are reference type. When you make change in it, it gets reflected in previously added values in colors.

You need to do

for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            int[] temp = new int[3];
            temp[0] = r;
            temp[1] = g;
            temp[2] = b;
            colors.Add(temp);
        }
    }
}

This way every temp will be a fresh instance and all values of colors will be different.

Upvotes: 4

Related Questions