1
class A
{
    public Color ColorA { get; set; }
    public Color ColorB { get; set; }

    public A(Color colorA, Color colorB)
    {
        ColorA = colorA;
        ColorB = colorB;
    }

    public override string ToString()
    {
        return ColorA + " " + ColorB;
    }
}

This renders as:

enter image description here


And this:

class A
{
    public Color ColorA { get; set; }
    public Color ColorB { get; set; }

    public A(Color colorA, Color colorB)
    {
        ColorA = colorA;
        ColorB = colorB;
    }

    public override string ToString()
    {
        return "Red" + " " + "Black";
    }
}

renders as:

enter image description here

Why the difference?

Edit: I know why the difference. My question is, how to achieve second result without hardcoding the text of the color.

sventevit
  • 4,766
  • 10
  • 57
  • 89
  • Try `return ColorA.ToString() + " " + ColorB.ToString();` the difference is likely due to the fact that it is calling ToString on the underlying type, ie `Color` in it's base implementation. – Adam Houldsworth Mar 08 '11 at 22:17

4 Answers4

3

The first method implicitly invokes ToString on the Color instances, while the second one is just you returning a string.

To your edit: I'm not sure, but I think it is done automatically. Otherwise, have a look into the ToKnownColor method, it returns a KnownColor enumeration, which you can use to construct a color with the behaviour you want. However, you should be aware of the fact that there won't be a name for every color possible.

Femaref
  • 60,705
  • 7
  • 138
  • 176
2

Try this:

return ColorA.Name + " " + ColorB.Name;
Zann Anderson
  • 4,767
  • 9
  • 35
  • 56
0

Because that's showing your ToString() result.

The first one calls Color.Red.ToString(), which gives 'Color [Red]', then Color.Black.ToString().

Rob
  • 26,989
  • 16
  • 82
  • 98
0

In the first instance, the ToString() method of the Color class is being called (giving the Color [ColorName] output).

andypaxo
  • 6,171
  • 3
  • 38
  • 53