0

I am working with RGB colour data in a C# (WPF) app, and find myself with a lot of cut and pasted code along the lines of

totals.red += currentPixel.red;
totals.green += currentPixel.green;
totals.blue += currentPixel.blue;

I'd like to reduce this copy-pasting and vulnerability to copy-paste errors. I could use arrays of size 3 around the place, but accessing those by number reduces readability.

I'd like to write something like this:

for (col = all colours) {
  totals[col] += currentPixel[col];
}

I'd know how to go about this in C, but am unfamiliar with C#. Something with enums?

Edit: Made the example make more sense.

3
  • What are red, thing, and otherthing? Commented Nov 21, 2012 at 16:33
  • Are red, green and blue all members of a type, or are just just hanging around on their own? If the former, which type, if the latter, why aren't they grouped together? Commented Nov 21, 2012 at 16:34
  • As others have commented, it's not clear what you are trying to achieve. I'd rather you write it out in C and have people help you translate the same to C#. Commented Nov 21, 2012 at 16:39

3 Answers 3

1

If you really want to use enums for this, you can do it this way:

enum Color { red, green, blue };

{
    foreach (int colorValue in Enum.GetValues(typeof(Color)))
        thing[colorValue] = otherthing[colorValue] * 2;
}

This would also allow you to grab an individual color by name in other code:

var color = thing[Color.red];
Sign up to request clarification or add additional context in comments.

1 Comment

This is the most promising so far, I think.
0

Assuming that red, green and blue are of type Color

You can setup a List of colours

List<Color> colors = new List<Color>();

Add items to it:

colors.Add(green);
colors.Add(blue);
colors.Add(red);

Then itterate:

foreach (Color color in colors)
{
    color.thing = color.otherThing * 2
}

Comments

0

Enums won't help here. But you can define your own type as done in Integer array or struct array - which is better?, and overload the arithmetic operators as described in http://msdn.microsoft.com/en-us/library/8edha89s(v=vs.80).aspx to allow multiplying to an int for example. E.g.

thing = otherthing * 2;

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.