Search code examples
c#classcastingradixderived

how to access properties in derived class stored in a list of the base class


I am trying to work with lists of objects that all come from the same base class.

I have my base type (question) and derived types (3TQ, 2TQ)

Depending on the situation the list will all be of one or other derived type.

So all my interfaces deal with a list of the base type question.

But once I have the list in my grasp, I cant access the derived types.

So long story short - how does one extract a usable derived object from the list of the base objects? I feel this should be easy and that I am missing something really obvious.


Solution

  • You will have to use explicit casting, the code would look like this,

    // This is the Child Class which derives from class Base.

    Child c = new Child();

    //UpCast can be done implicitly without any issues

    Base b = c;

    //Explicit conversion is required to cast the object back to derived.
    Child c1 = (Child) b;

    Now , since this is runtime operation, you will not get an error in case of incorrect casting, hence always make a check before casting. you can use "is" or "as" keyword, Below are the links that will give you more details.

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is

    Hope this helps