Overriding a virtual method in a type with a conversion method

When I write Console.WriteLine( new Point (1,1)); It does not call the ToString method. But it converts the object to Int32 and writes it to the console. But why? It seems to be ignoring the overridden ToString method.

 struct Point { public Int32 x; public Int32 y; public Point(Int32 x1,Int32 y1) { x = x1; y = y1; } public static Point operator +(Point p1, Point p2) { return new Point(p1.x + p2.x, p1.y + p2.y); } public static implicit operator Int32(Point p) { Console.WriteLine("Converted to Int32"); return py + px; } public override string ToString() { return String.Format("x = {0} | y = {1}", x, y); } } 
+7
c #
source share
2 answers

The reason is related to the implicit conversion to Int32 (as you probably know).

Console.WriteLine has many overloads that accept String , Object and others, including Int32 .

Since Point implicitly converted to Int32 , int overloading Console.WriteLine , which also implies implicit casting.

This can be fixed as follows:

 Console.WriteLine(new Point(1, 1).ToString()); Console.WriteLine((object)new Point(1, 1)); 

This can be found in Overload Reservation in C # .

Otherwise, the best member of the function is one member of the function, which is better than all other members of the function with respect to this list of arguments, provided that each member of the function is compared with all other members of the function using the rules in Section 7.4.2.2 .

What else has:

7.4.2.2 Improved Feature Element

for each argument, the implicit conversion from AX to PX is not worse than the implicit conversion from AX to QX, and

+8
source share

This is due to implicit conversion in your structure type, i.e. in the following lines:

 public static implicit operator Int32(Point p) { Console.WriteLine("Converted to Int32"); return py + px; } 

So, the compiler treats your Point type as a whole, invoking the above implicit conversion method.

To fix this, you need to either remove the implicit conversion from your type, or use the ToString () method by executing Console.WriteLine ()

This should fix your problem. Hope this helps.

The best

+2
source share

All Articles