views:

76

answers:

3

Hello,

I'm creating my own type for representing css values (like pixels eg. 12px ). To be able to add/subtract/multiply/... my type and ints I've defined two implicit operators to and from int. Everything works great except one thing.. If I write:

CssUnitBase c1 = 10;
Console.WriteLine(c1);

I get "10" instead of "10px" - implicit conversion to int is used instead ToString() method. How can I prevent that?

+1  A: 

Override the "ToString()" method and use c1.ToString().

Carra
+8  A: 

Yes, there's an implicit conversion to int and the overload of WriteLine(int) is more specific than WriteLine(object), so it'll use that.

You could explicitly call the WriteLine(object) overload:

Console.WriteLine((object)c1);

... or you could call ToString yourself, so that Console.WriteLine(string) is called:

Console.WriteLine(c1.ToString());

... or you could just remove the implicit conversion to int. Just how useful is it to you? I'm generally not in favour of implicit conversions for this sort of thing... (You could keep the implicit conversion from int of course, if you really wanted to.)

Jon Skeet
I've done that quite another way. Implicit conversion to int is now explicit and I have 4 operators (+-*/) overloaded that operate on CssUnitBase. This way I have both - ToString is called by default and arithmetic operations are working well(on mixture of int and CssUnitBase operands) without much code. All operations like CssUnitBase * int should always return CssUnitBase so this is in every aspect the way I want it.
kubal5003
@kubal5003: That sounds like the right way of doing things, yes. Glad it worked out for you.
Jon Skeet
+1  A: 

Just override the ToString method in CssUnitBase and call that when you want it as a string.

ho1
I've already done that!
kubal5003