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;
}
}
}
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
The derived instance IS the base instance. It's just one object instance in memory.
example:
thing
is an instance of anA
, and is also an instance of aB
.You could for example, write this line:
B thing2 = thing;
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
}
If you're working with an instance of the derived class, there is no
base instance
. An example:What is not possible within
B
:You can do something like this:
And you can add another method like
And then you can
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 ofA
, but it does not consist of an instance ofB
which holds an (hidden but automatic) reference to an instance ofA
. You can cast yourB
instance toA
, but it remains to be an instance ofB
.Well you not provide code for your question, but i supsect you want something like
But keep in mind that
MyBase
is really of typeDerived