tags:

views:

64

answers:

2

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 ?

+3  A: 

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.

Simon Steele
Thanks..........
+6  A: 

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.

Jon Skeet
Thanks............