Color comparer mystery

A

Andrew

The following code gets colors and sorts them. When calling
GetColorsSorted() it uses the ColorComparer to compare each color.

In VS2008 on XP when running with the "Debug" build the compare has a
different number of iterations to when running under a "Release" build. I
can't understand why this would be.

When the program was run on Vista the "Debug" version worked (again with a
different no of iterations) but the "Release" version hung forever because
the comparer never produced a zero return when it found the same items.

Why would the float variables get different values between the "Debug" and
"Release" builds?

Can anyone understand why it would never drop through to the zero return?

I have now fixed this, see the bottom for details.

Here is the code:

public static IEnumerable<Color> GetColors()
{
foreach (PropertyInfo PInfo in typeof(Color).GetProperties())
if (PInfo.PropertyType == typeof(Color))
if (PInfo.Name != "Transparent")
if (PInfo.Name != "Empty")
yield return Color.FromName(PInfo.Name);
}

public static IEnumerable<Color> GetColorsSorted()
{
List<Color> List = new List<Color>();

List.AddRange(GetColors());

List.Sort(new ColorComparer());

foreach (Color C in List)
yield return C;
}

internal class ColorComparer : IComparer<Color>
{
#region IComparer Members

public int Compare(Color x, Color y)
{
float hx, hy, sx, sy, bx, by;

// get saturation values
sx = x.GetSaturation();
sy = y.GetSaturation();
// get hue values
hx = x.GetHue();
hy = y.GetHue();
// get brightness values
bx = x.GetBrightness();
by = y.GetBrightness();

// determine order
// 1 : hue
if (hx < hy)
return -1;
else if (hx > hy)
return 1;
else
{
// 2 : saturation
if (sx < sy)
return -1;
else if (sx > sy)
return 1;
else
{
// 3 : brightness
if (bx < by)
return -1;
else if (bx > by)
return 1;
else
return 0;
}
}
}
#endregion
}


To fix this I added the following code at the top of the comparer:
if (x.ToArgb() == y.ToArgb())
return 0;
 
J

jp2msft

That's neat code, Andrew. You've got a few more years under your belt than I
do.

I'm going to go see what "yield" means, now. ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top