Question

This is VS2010 and .NET 4.0. I'm trying to compare two System.Drawing.Color objects.

The value of mStartColor.ToArgb() is 16777215.

The value of Color.Transparent.ToArgb() is 16777215.

The value of mStartColor <> Color.Transparent is True.

How is equality implemented for Color objects?

EDIT

Thanks everyone. I got my answer, though it doesn't make much sense to me (see my comments to Tim's and Dave's answers below). I'll mark Tim's post as the answer and he was the first to reply, but Dave's answer is equally informative.

Was it helpful?

Solution

Always read the documentation first:

"To compare colors based solely on their ARGB values, you should use the ToArgb method. This is because the Equals and Equality members determine equivalency using more than just the ARGB value of the colors. For example, Black and FromArgb(0,0,0) are not considered equal, since Black is a named color and FromArgb(0,0,0) is not"

OTHER TIPS

Colour structs have more data contained in them, than just the actual colour information, such as

Color [Transparent] 
R: 255 
G: 255 
B: 255 
A: 0 
IsKnownColor: True 
IsEmpty: False 
IsNamedColor: True 
IsSystemColor: False 
Name: Transparent 

Color.FromArgb(16777215)

Color [A=0, R=255, G=255, B=255] 
R: 255 
G: 255 
B: 255 
A: 0 
IsKnownColor: False 
IsEmpty: False 
IsNamedColor: False 
IsSystemColor: False 
Name: ffffff 

Equals comparisons will use all of these to determine equality. you should be diong what you already suggested, and use:

Color.Transparent.ToArgb().Equals(mStartColor.ToArgb())

You could write an extension method which would compare the ARGB value of two colour objects and return true if they are the same.

Here is the MSDN Documentation on extension methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top