Reputation: 14736
I came across these lines of code
ClassA classAObject;
//some lines of code that hydrate 'classAObject'
DerivedFromClassA derivedObject = classAObject as DerivedFromClassA;
whats going on, on the last line? Is it assigning to derivedObject only those values that are in common between derivedObject and classAObject ?
Upvotes: 3
Views: 192
Reputation: 1500923
No, it's broadly equivalent to:
DerivedFromClassA derivedObject = null;
if (classAObject is DerivedFromClassA)
{
derivedObject = (DerivedFromClassA) classAObject;
}
In other words, the result will either be a null reference, or a reference to the same object, but statically typed to be of the derived type.
Upvotes: 6
Reputation: 11608
No, it's accessing the same object, but you now have access to the parts of that object from type DerivedFromClassA
. There is only one object.
Additionally, if classAObject is not an instance of DerivedFromClassA
or a type derived from it, then derivedObject will be null, as there's no valid cast.
Upvotes: 3