Given the following code:
using System;
namespace Test721
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(new A()); //prints 666
Console.WriteLine(new B()); //prints 666
Console.ReadLine();
}
}
public class A
{
public static implicit operator int(A a)
{
return 666;
}
}
public class B : A
{
public static implicit operator double(B b)
{
return 667;
}
}
}
the results are as in the comments - both lines print 666.
I'd expect Console.WriteLine(new B());
to write 667, while there is a double
overload of Console.WriteLine
.
Why is that happening?
This is covered in section 7.4.3.4 of the 3.5 C# language spec. This section deals in overload resolution and how conversions are considered in this process. The applicable line is
If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion.
In this case there is an implicit conversion from B
to both int
(T1) and double
(T2). There is an implicit conversion from int
to double
but not the other way around. Hence the implicit conversion from B
to int
is considered better and wins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With