Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare SolidColorBrushes?

Tags:

c#

wpf

I am trying to Compare 2 Brushes as you can see in the Picture. I have no Idea why its failing...

Equal Fail

like image 539
Bulli Avatar asked Feb 12 '23 02:02

Bulli


2 Answers

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!
}
like image 114
Niels Filter Avatar answered Feb 13 '23 20:02

Niels Filter


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:

  • https://msdn.microsoft.com/en-us/library/system.windows.media.solidcolorbrush%28v=vs.110%29.aspx
  • https://msdn.microsoft.com/en-us/library/aa345743(v=vs.110).aspx
like image 25
Caramiriel Avatar answered Feb 13 '23 20:02

Caramiriel