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.