Search code examples
c#classinheritanceabstract

C# Access base class variables/functions from abstract class


Maybe its not possible or i am mixing something up, but its breaking my head.

Let's say, we got an abstract class A and a class B based of A. Is it possible for A to access variables/functions from B?

Example:

 abstract class A
 {
    public bool activeA = false;

    public bool getState()
    {
        return test; // The variable from class B
    }
 }

 class B : A
 {
    public bool test = true;

    public void isActive()
    {
         return base.getState(); // So this should return true because getState() should access the variable test^^
    }

 }

Solution

  • No, this is not possible. A doesn't know anything about B or potentially C..Z.

    If test would be on A, then both A and B could access it. Or you could create an interface that's implemented by B and that A knows about and pass B as a parameter to A.

    This could look like this:

    interface IB
    {
        bool Test { get; }
    }
    
    abstract class A
    {
       public bool activeA = false;
    
       public bool getState(IB arg)
       {
           return arg.Test;
       }
    }
    
    class B : A, IB
    {
       public bool Test => true;
    
       public bool isActive()
       {
             return base.getState(this); 
        }
     }