4

I have 2 classes which implement the same interface. But somehow I cannot cast them from one to another.

Here's an example:

public interface IObject {
    // ...
}

public class FooObject : IObject {
    // ...
}

public class BarObject : IObject {
    // ...
}

-

If I do it like this, VS will mark it as Cannot convert type 'FooObject' to 'BarObject'

var foo = new FooObject();
var bar = (BarObject)foo; // Build error

-

If I do it like this, there is no build error, but when called, it throw System.InvalidCastException: Unable to cast object of type 'FooObject' to 'BarObject'.

var foo = new FooObject();
var bar = (BarObject)(IObject)foo; // No build error, but InvalidCastException gets thrown

-

So, how do I cast/parse/convert an implementation (FooObject) of an interface (IObject) to another implementation (BarObject) of that same interface?

Solution:

I fixed this by creating an explicit conversion operator:

public class FooObject {
    // ...
    public static explicit operator BarObject(FooObject fooObject)
    {
        // ...
    }
}

Thanks to CodeCaster.

Mason
  • 1,007
  • 1
  • 13
  • 31
  • 2
    You can't. Both `Cat` and `Dog` can implement `IAnimal`, but you can't cast one to the other - at least not without writing implicit or explicit conversion operators. What problem are you _actually_ trying to solve? – CodeCaster Mar 07 '19 at 15:31
  • @CodeCaster, I created a ```public static explicit operator BarObject(FooObject fooObject)``` and that did the trick. Thanks! – Mason Mar 07 '19 at 15:41
  • 1
    I just made a similar suggestion here: https://stackoverflow.com/a/55047697/880990. – Olivier Jacot-Descombes Mar 07 '19 at 15:51
  • If you use this extension method, you probably will be right: https://stackoverflow.com/questions/3672742/cast-class-into-another-class-or-convert-class-to-another – MohammadReza Hasanzadeh Mar 07 '19 at 16:15
  • 1
    @Olivier nice, that's what that duplicate was missing. – CodeCaster Mar 07 '19 at 16:23

0 Answers0