Search code examples
c#polymorphismdowncastupcasting

C# Upcasting / Polymorphism Issue


I believe this question is fairly basic but I am having trouble finding an answer to this question. In C# let's say I have 3 classes: A, B, C

B derives from A

C derives from B

Now, if I wanted a list or array of objects of type class A but wanted the array to be able to house objects of type B and C this is no problem... I could do something like this:

A[] myArrayofAtypes;

However let's say I make the first element of this array of type C. If type C has a variable defined in its class definition that ONLY exists in class C's class definition... how do I access that variable from the array? I can't just do A[0].MyVariableGetter as that variable does not exist in the base class, A.

Any suggestions?


Solution

  • You have to downcast it:

    C c = (C)myArrayofAtypes[0];
    var v = c.MyVariableGetter;