kubal5003
kubal5003

Reputation: 7254

C# Implicit operators and ToString()

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?

Upvotes: 6

Views: 2883

Answers (3)

Hans Olsson
Hans Olsson

Reputation: 55009

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500375

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.)

Upvotes: 14

Carra
Carra

Reputation: 17964

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

Upvotes: 1

Related Questions