Search code examples
c#listderived-classabstract-data-type

How to access member variable of derived class from an abstract list in C#


this is the code for the base class:

public abstract class baseClass
{
    public string Name { get; set; }
}

then there are two derived classes

public derived1: baseClass 
{
    public int derivedMemberVariable { get; set; }
}

public derived2: baseClass 
{
    public string derivedMemberVariableAlternative { get; set; }
}

I then created a list of the base class and add both derived types to it:

List<baseClass> baseList = new List<baseClass>();
derived1 der1 = new derived1{
    Name = "Derived1 Name",
    derivedMemberVariable = 10
};
derived2 der2 = new derived2{
    Name = "Derived2 Name",
    derivedMemberVariable = "STRING"
};

baseList.Add(der1);
baseList.Add(der2);

foreach (b in baseList){
    b.derivedMemberVariable //this is what fails
}

how can I access this derived member variable from the list created with the base class??

I have to use the code the way it is because it is for a school project so I cant modify the way the classes work but I think I can modify the list? but the list needs to contain both of the derived classes.

am I going to be able to accomplish this or is there a different approach id have to take?

ok, so for some reason as soon as I tried to cast this time it worked! I feel dumb :/

thanks to AntiTcb for pointing it out.

what I ended up doing was:

foreach (b in baseList){
    if(b.GetType() == der1.GetType()){
        var q = b as derived1;
        q.derivedMemberVariable; // now works
    }
    if(b.GetType() == der2.GetType()){
        var q = b as derived2;
        q.derivedMemberVariableAlternative; // now works
    }
}

Solution

  • Use pattern matching:

    foreach (b in baseList){ 
    {
          if(b is DerivedType d) 
          {
                 d.derivedMemberVariable //this is  what fails 
          } 
    }