In C# I'm in a scenario with the following types provided by the environment:
public interface IFoo {
}
public abstract class Base {
}
public class Derived : Base, IFoo {
}
public class Arbitrary {
public Base GetBase() { }
}
Here's what I've written in addition to this. Note that I can guarantee in my code that Arbitrary.GetBase()
will always return an instance of Derived
.
public class Arbitrary2 : Arbitrary {
public IFoo GetDerived() {
return (IFoo)base.GetBase();
}
}
However this code fails with the message "Cannot convert type 'Base' to 'IFoo'".
But if I do this then it works:
public class Arbitrary2 : Arbitrary {
public IFoo GetDerived() {
Object baseAsObject = base.GetBase();
return (IFoo)baseAsObject ;
}
}
Why is this upcast to Object necessary before I downcast it to IFoo? The two pieces of code are functionally identical, and the latter will reliably crash at runtime if the cast is invalid. I don't understand why the compiler complains.
Base
does not derive fromIFoo
, you shouldn't cast to/from it.object
.