Compare two Color objects
Solution 1
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"
Solution 2
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())
Related videos on Youtube
dotNET
Programming since the days of FoxPro 2.0 and Windows 98, all the way through VB4, 5, 6. Started working with .NET in 2004 and never looked back. WinForms, OOP, SQL Server and MS-Office programming (both VBA and VSTO) have been my primary areas of interest. Trying to switch to WPF and MVVM now-a-days. Love studying Islam, literature (especially Urdu) and spending some time on SO each day.
Updated on September 15, 2022Comments
-
dotNET over 1 year
This is VS2010 and .NET 4.0. I'm trying to compare two
System.Drawing.Color
objects.The value of
mStartColor.ToArgb()
is16777215
.The value of
Color.Transparent.ToArgb()
is16777215
.The value of
mStartColor <> Color.Transparent
isTrue
.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 over 10 yearsThanks. 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 over 10 yearsThanks 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?
-
Tim Schmelter over 10 years@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 sameKnownColor
. -
Dave Bish over 10 yearsI would assume that all of the "System" colours are pre-defined as constants