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
In this case there is an implicit conversion from
Bto bothint(T1) anddouble(T2). There is an implicit conversion frominttodoublebut not the other way around. Hence the implicit conversion fromBtointis considered better and wins.