Reputation: 6882
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.
Upvotes: 0
Views: 615
Reputation: 19496
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];
Upvotes: 1
Reputation: 3013
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;
Upvotes: 0
Reputation: 66
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
}
Upvotes: 0