0

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
    }
}
  • What do you expect to happen when you try to access `derived2`'s `derivedMemberVariable` (which does not exist) during the second iteration of the foreach loop? – clcto Nov 06 '18 at 21:57
  • 2
    You need to cast `b` to the appropriate type to access that type's members. – AntiTcb Nov 06 '18 at 21:57
  • I would like to only access the member variable if it exists, and I haven't had any luck with figuring out how to cast it. – CaptainAmericaIRL Nov 06 '18 at 21:59
  • 1
    You should consider using a `virtual` or `abstract` property to let the derived class override or implement it (respectively) and access it after that. Otherwise you need to first verify the derived class is of the expected type then you can cast it and access property: `(b is derived1) ? (b as derived1).derivedMemberVariable : (b as derived2).derivedMemberVariableAlternative ;` (and make sure to consider other types). In that example, the important keywords are `is` and `as`. – Elaskanator Nov 06 '18 at 22:04

1 Answers1

1

Use pattern matching:

foreach (b in baseList){ 
{
      if(b is DerivedType d) 
      {
             d.derivedMemberVariable //this is  what fails 
      } 
}
fstam
  • 669
  • 4
  • 20