Search code examples
c#.netinheritancederived-classbase-class

How to Get Base Class Instance from a Derived Class


I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.

Example Code

public class SuperParent
{
    public int SPID;

    public SuperParent()
    {
    }
}

public class SubChild : SuperParent
{
    public SubChild(int pSPID)
    {
        base.SPID = pSPID;
    }

    public int BaseSPID
    {
        get
        {
            SuperParent sp = base;
            return sp.SPID;
        }
    }
}

Solution

  • If you're working with an instance of the derived class, there is no base instance. An example:

    class A
    {
        public void Foo() { ... }
    }
    
    class B : A
    {
        public void Bar() { ... }
    }
    

    What is not possible within B:

    public void Bar()
    {
        // Use of keyword base not valid in this context
        var baseOfThis = base; 
    }
    

    You can do something like this:

    public void Bar()
    {
        base.Foo();
    }
    

    And you can add another method like

    public A GetBase()
    {
        return (A)this;
    }
    

    And then you can

    public void Bar()
    { 
        var baseOfThis = GetBase();
        // equal to:
        baseOfThis = (A)this;
    }
    

    So this GetBase() method is probably what you want.

    The punchline is: If you have an instance of B, it inherits all properties and the non-overriden behaviour of A, but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A. You can cast your B instance to A, but it remains to be an instance of B.