Search code examples
c#language-specifications

Why does an extension method bypass the need for explicit conversion?


I have an explicit conversion setup between two reference types.

class Car
{
    public void Foo(Car car)
    {

    }

    public static explicit operator Bike(Car car)
    {
        return new Bike();
    }

}

class Bike
{

}

If I invoke Foo and pass a type of Bike, then I must perform an explicit conversion.

            Car myCar = new Car();
            Bike bike = (Bike)myCar;            
            myCar.Foo(bike);//Error: Cannot convert from Bike to Car.

However, if I add an extension method, then explicit conversio is no longer required.

        public static void Foo(this Car car, Bike bike)
        {
            car.Foo(bike);//Success...
        }

Why is the extension method able to invoke Foo with a type of Bike implicitly?


Solution

  • Now that you've modified the code to show;

    public static void Foo(this Car car, Bike bike)
    {
        car.Foo(bike);//Success...
    }
    

    All you've done is create an ironic StackOverflowException. This method is now just calling itself recursively, not the implementation of Foo in Car.

    TIP: Get yourself a copy of ReSharper - it'll put a nice circle-arrow icon on this line of code to show you what's going on without actually needing to compile or run it. :-)