0

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);
        }
    }
}

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It works, but I'm also interested in why it doesn't when I create the array before and just replace the values inside it. Does it have to do with the way lists work?
10 minute waiting period.
2

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));
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.