views:

884

answers:

4

This does not work

        int blueInt = Color.Blue.ToArgb();
        Color fred = Color.FromArgb(blueInt);
        Assert.AreEqual(Color.Blue,fred);

Any suggestions?

[Edit]

I'm using NUnit and the output is

failed:

Expected: Color [Blue]

But was: Color [A=255, R=0, G=0, B=255]

[Edit]

This works!

        int blueInt = Color.Blue.ToArgb();
        Color fred = Color.FromArgb(blueInt);
        Assert.AreEqual(Color.Blue.ToArgb(),fred.ToArgb());
A: 

I would have expected this with Assert.AreSame because of the boxing with the value types, but AreEqual should not have this problem.

Could you add which language (I'm assuming C#) your using and which testing framework?

What does Assert.AreEqual(true, Color.Blue == fred); result in?

Davy Landman
Yes - it is c#Using NUnit and the output is:failed: Expected: Color [Blue] But was: Color [A=255, R=0, G=0, B=255]
+9  A: 

From the MSDN documentation on Color.operator ==:

This method compares more than the ARGB values of the Color structures. It also does a comparison of some state flags. If you want to compare just the ARGB values of two Color structures, compare them using the ToArgb method.

I'm guessing the state flags are different.

lc
@lc: The state flags are different because the static Blue property returns a named color, whereas ToArgb does not retain the fact that the color is named, the int only retains the ARGB info. When converting back to a color, the name is lost, hence the reason why equal does not return true.
casperOne
@casperOne: Thanks for the further explanation. I thought it had to do with the name, but to be honest, I wasn't exactly sure. This clears it up.
lc
Thanks to both of you.
+1  A: 

They won't equal the same, as Color.Blue doesn't equal your colour object, it equals something stored internally, a "new Color(KnownColor.Blue);" to be exact.

Chris S
A: 

Alternatively, this also works, and I think it's more intuitive

    [Test]
    public void ColorTransform()
    {
        var argbInt = Color.LightCyan.ToArgb();
        Color backColor = Color.FromArgb(argbInt);
        Assert.AreEqual(Color.LightCyan.A, backColor.A);
        Assert.AreEqual(Color.LightCyan.B, backColor.B);
        Assert.AreEqual(Color.LightCyan.G, backColor.G);
        Assert.AreEqual(Color.LightCyan.R, backColor.R);
    }
Ngu Soon Hui