C # Implicit Operators and ToString ()

I create my own type to represent css values โ€‹โ€‹(e.g. pixels, e.g. 12px). To be able to add / subtract / multiply / ... my type and ints, I defined two implicit operators in and out of int. Everything works fine except for one. If I write:

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

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

+6
c # operator-overloading implicit-cast
source share
3 answers

Yes, there is an implicit conversion to int , and the WriteLine(int) overload is more specific than WriteLine(object) , so it will use this.

You can explicitly call WriteLine(object) overload:

 Console.WriteLine((object)c1); 

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

 Console.WriteLine(c1.ToString()); 

... or you can just remove the implicit conversion to int . How useful is this to you? I'm generally not a supporter of implicit conversions for this kind of thing ... (Of course, you could keep the implicit transform with int if you really wanted to.)

+12
source share

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

+1
source share

Just override the ToString method in CssUnitBase and call it when you want it to be like a string.

+1
source share

All Articles