Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding virtual method in type with conversion method

Tags:

c#

.net

When I write Console.WriteLine( new Point (1,1)); it doesn't call method ToString. But it converts object to Int32, and write it to console. But why? It seems as it ignores overridden method ToString.

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 p.y + p.x;
    }

    public override string ToString()
    {
        return String.Format("x = {0}  |  y = {1}", x, y);
    }
}
like image 717
YV17 Avatar asked Jan 22 '16 20:01

YV17


Video Answer


2 Answers

The reason is due to implicit conversion to Int32 (As you probably know).

Console.WriteLine has many overloads which takes String, Object and others including Int32.

Since Point is implicitly convertible to Int32 the int overload of Console.WriteLine is used, which does the implicit casting as well.

This can be fixed by:

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

You can find more about it in Overload Resolution in C#.

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

Which further has:

7.4.2.2 Better function member

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

like image 87
Habib Avatar answered Oct 09 '22 10:10

Habib


This is because of the implicit conversion in your struct type i.e. the following lines:

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

So the compiler is considering your Point type as an integer by invoking the above implicit conversion method.

To fix this, you need to either remove the implicit conversion from your type or put a ToString() method while doing Console.WriteLine()

This should fix your issue. Hope this helps.

Best

like image 21
frostedcoder Avatar answered Oct 09 '22 10:10

frostedcoder