Search code examples
c#castingupcasting

In C# Do I Ever Have to Perform An Explicit Upcast?


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?


Solution

  • If you have

    class B { }
    class S : B { }
    class T : B { }
    

    and you try to do something like

    var b = myBool ? new S() : new T();
    

    this won't compile unless you explicitly cast either the S or the T instance (or both) to B.

    The same goes for anonymous methods; this

    new bool[0].Select(b => 
        { if (b) { return new S(); } else { return new T(); } });
    

    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

    class B { public void DoSomething() { } }
    class S : B { public new void DoSomething() { } }
    

    then

    S s = new S();
    s.DoSomething();       // calls the S version
    ((B)s).DoSomething();  // calls the B version