Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance base class reference C#

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?"

like image 433
Nikita Avatar asked Nov 27 '22 04:11

Nikita


2 Answers

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

like image 67
Adam Houldsworth Avatar answered Dec 15 '22 00:12

Adam Houldsworth


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

like image 41
Bala R Avatar answered Dec 14 '22 23:12

Bala R