Home > front end >  Access attribute of derived class when base class instance is passed
Access attribute of derived class when base class instance is passed

Time:04-22

I have got an Array of a Base-Class that contains objects of two derived classes.

Problem: How do I access the attributes of one of the derived classes when the passed object does not specify the type?

*getter and setter properties are in place

class BaseClass{ }
class DerivedClass1 : BaseClass 
{
    var attribute;
    DerivedClass(var attribute)
    {
         this.attribute = attribute;
    }
    var attribute{ get; set;}
}

class DerivedClass2
{
     //Constructor, Code and other attributes
}

class Programm
{
     BaseClass[] bc = {new DerivedClass1(<var>), new DerivedClass2(), new DerivedClass1(<othervar>)}
     
     public void method(BaseClass[] bc)
     {
         //Here I would have wanted to be able to access the attribute in a fashion something like 
         //'bc[0].attribute' but could not figure out how to do it as bc[] has the 
         //type of the BaseClass which does not contain the wanted attribute
     }
}

CodePudding user response:

Use pattern matching, like so:

class BaseClass{ }
class DerivedClass1 : BaseClass 
{
    int attribute;
    public DerivedClass1(int attribute)
    {
         this.attribute = attribute;
    }
    public int Attribute{ get; set;}
}

class DerivedClass2 : BaseClass
{
     //Constructor, Code and other attributes
    public DerivedClass2() {}
}

class Programm
{
     BaseClass[] bc = {new DerivedClass1(2), new DerivedClass2(), new DerivedClass1(0)};
     
     public void method(BaseClass[] bc)
     {
         for (var i = 0; i < bc.Length; i  )
         {
             if (bc[i] is DerivedClass1 dc)
                 dc.Attribute = 1;
         }
     }
}

When you check the type of the variable and give it a new name (dc in this context) the compiler knows it is the derived class and treats it as such. Just make sure you are using the name you gave it in the if statement when you access the derived class's attributes and methods.

CodePudding user response:

:pattern matching seems to be a good (probably way better) solution

:However I found - after a long time of endless trying - that typecasting works perfectly fine as well. For my example that would be something along the lines of:

//inside of the method 'method(BaseClass[] bc)'
for(var i = 0; i<bc.Length; i  )
{
    if(bc[i].GetType == typeof(DerivedClass1))
    {
        ((DerivedClass1)bc[i]).Attribute =...
    }
}

  • Related