class Base
{
//...
public int i = 5;
}
class Drifted : Base
{
//...
public int b = 10;
}
Base ObjectOrReference = new Drifted();
So Base ObjectOrReference;
is reference to the base type.
When we write Base ObjectOrReference = new Drifted();
it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference
object?"
It's still a reference, a pointer to the object on the heap. It is of type Drifted
.
Even though your reference is of the Base
type, the underlying object is Drifted
and any overridden members in the derived class Drifted
will be used instead of those on Base
, even though you are trying to use Base
.
In the case of member hiding using the new
syntax, if you have a reference to the base type it will bypass any derived classes that are hiding the members.
An overview can be found online with Googling for "C# Reference Types". I skimmed this, looks like a worthwhile read:
http://www.albahari.com/valuevsreftypes.aspx
Base ObjectOrReference = new Drifted();
with that, you have created a Drifted
instance but is referenced by Base
reference variable ObjectOrReference
. Right now it's capabilities are limited to that of what's available in Base
. If you want to, say access int b
in Drifted
, you'll have to cast it to Drifted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With