OOP what happens here in this assignment

I came across these lines of code

ClassA classAObject;
//some lines of code that hydrate 'classAObject'
DerivedFromClassA derivedObject = classAObject as DerivedFromClassA;

What happens on the last line? Does the derived object only assign values ​​that are common between the derived objects and classAObject?

+3
source share
2 answers

No, this is generally equivalent to:

DerivedFromClassA derivedObject = null;
if (classAObject is DerivedFromClassA)
{
    derivedObject = (DerivedFromClassA) classAObject;
}

In other words, the result will be either an empty reference or a reference to the same object, but statically typed for the derived type.

+6
source

No, it accesses the same object, but now you have access to parts of this object from the type DerivedFromClassA. There is only one object.

, classAObject DerivedFromClassA , outputObject null, .

+3

Source: https://habr.com/ru/post/1771713/


All Articles