20

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.

dotNET
  • 33,414
  • 24
  • 162
  • 251

3 Answers3

22

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"

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 2
    Thanks. It does help (in fact a precise answer), but doesn't make much sense to me. If they are equivalent for all practical purposes, why would their objects not be equal? – dotNET Jan 08 '14 at 11:53
  • @dotNET: because they are not the same colors in a strict manner. I don't know where `Color.Equals` or Color-`==` is used everywhere. So even if a color look like another it's not the same if it hasn't for example the same name or the same `KnownColor`. – Tim Schmelter Jan 08 '14 at 11:56
18

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())
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
  • Thanks Dave. Roughly the same as Tim's answer below. What I don't like is that all the other fields you have listed are read-only, and presumably compute their values directly based on the values of A, R, G and B. So why wouldn't Equals() work the way we expect it to? – dotNET Jan 08 '14 at 11:55
  • I would assume that all of the "System" colours are pre-defined as constants – Dave Bish Jan 08 '14 at 11:57
0

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.

TylerD87
  • 1,588
  • 11
  • 20