Reputation: 44275
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?
Upvotes: 0
Views: 174
Reputation: 250822
Shouldn't your explicit conversion should be defined on Bike?
class Bike
{
public static explicit operator Bike(Car car)
{
return new Bike();
}
}
This allows:
Car myCar = new Car();
Bike myBike = (Bike) myCar;
If you want to be able to do this without specifying the conversion, you should use the implicit
keyword.
Car myCar = new Car();
Bike myBike = myCar;
And finally, where you are getting the error //Error: Cannot convert from Bike to Car.
This indicates you need the inverse conversion...
class Car
{
// FROM Bike TO Car
public static explicit operator Car(Bike bike)
{
return new Car();
}
}
Upvotes: 0
Reputation: 6527
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. :-)
Upvotes: 4
Reputation: 203802
Why is the extension method able to invoke Foo with a type of Bike implicitly?
It's not. The code you provided results in a compiler error.
At least one of the following is true:
Upvotes: 6