Given a class hierarchy with a base class B and a subclass S:
class B { }
class S : B { }
I can assign a S to an B with an implicit conversion:
B b = new S();
If I wanted to downcast this back to a S I would have to do this explicitly:
B b = new S();
...
S s = (S)b;
Now, my understanding is we can guarantee that there is always assignment compatibility going from S to B, so we will never have to perform an explicit upcast in the following way:
S s = new S();
B b = (B)s; // or
B b2 = s as B;
Is this assertion correct, or as the question states Do I Ever Have to Perform An Explicit Upcast?
If you have
and you try to do something like
this won’t compile unless you explicitly cast either the
Sor theTinstance (or both) toB.The same goes for anonymous methods; this
won’t compile without casts (or specifying
Select<bool, B>but this might not be possible, for example if your source is an anonymous type).Also, if you have
then