Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion rules for overloaded conversion operators

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?

like image 397
Piotr Zierhoffer Avatar asked Feb 08 '13 17:02

Piotr Zierhoffer


1 Answers

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.

like image 127
JaredPar Avatar answered Sep 21 '22 16:09

JaredPar