Information Technology Reference
In-Depth Information
Reference Conversions
As you well know by now, reference type objects comprise two parts in memory: the reference
and the data.
￿
Part of the information held by the reference is the type of the data it is pointing at .
￿
A reference conversion takes a source reference and returns a reference pointing at the
same place in the heap, but “labels” it as a different type.
For example, the following code shows two reference variables, MyVar1 and MyVar2 , that
point to the same object in memory. The code is illustrated in Figure 18-17.
￿To MyVar1 , the object it references looks like an object of type B —which it is.
￿To MyVar2 , the same object looks like an object of type A .
- Even though it is actually pointing at an object of type B , it cannot see the parts of B
that extend A , and therefore cannot see Field2 .
-The second WriteLine statement would, therefore, cause a compile error.
Notice that the “conversion” does not change MyVar1 .
class A { public int Field1; }
class B: A { public int Field2; }
class Program {
static void Main( )
{
B MyVar1 = new B();
Return the reference to MyVar1 as a reference to a class A.
A MyVar2 = (A) MyVar1;
Console.WriteLine("{0}", MyVar2.Field1); // Fine
Console.WriteLine("{0}", MyVar2.Field2); // Compile error!
}
} MyVar2 can't see Field2.
Search WWH ::




Custom Search