I am trying to Compare 2 Brushes as you can see in the Picture. I have no Idea why its failing...
They won't be equal because it's doing a reference comparison and they are two different references in the heap with the same properties.
If you want to control object comparisons, you should implement the IEqualtable
interface. You can then say how the objects must be compared. In this case however, since SolidColorBrush
is a .NET class, we cannot implement IEquatable
. There are different options
1) Use an extension method on the SolidColorBrush
which compares a brush instance with another. Not a very good solution in this case though.
2) The best bet would proably be to use IEqualityComparer
interface. You create a seperate class implementing IEqualityComparer
, which will define how to compare 2 different objects. For instance in your example, you may want to compare the SolidColorBrush on Color and Opacity:
public class SolidColorBrushComparer : IEqualityComparer<SolidColorBrush>
{
public bool Equals(SolidColorBrush x, SolidColorBrush y)
{
return x.Color == y.Color &&
x.Opacity == y.Opacity;
}
public int GetHashCode(SolidColorBrush obj)
{
return new { C = obj.Color, O = obj.Opacity }.GetHashCode();
}
}
And then to compare you simply do the following:
SolidColorBrush otherBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFEFEEEE"));
SolidColorBrush backgroundBrush = (SolidColorBrush)grd.Background;
if(new SolidColorBrushComparer().Equals(backgroundBrush, otherBrush))
{
// They're equal, Yay!
}
Classes derived from DependencyObject
will only be equal (.Equals() == true
) if the object has the same reference (overloading not included). This can only be the case if the actual same object was used, or BrushConverter.ConvertFrom
was returning the same instances of the SolidColorBrush
. This case is unlikely, and would be an assumption.
Like comments already mentioned: try to compare the Color
and/or other properties of the solid color brush. Color
is a struct that implements IEquatable<Color>
and will result in the correct behavior.
Sources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With