9.2 Reference types


Reference types in C# are identical to Java reference types “ they refer to objects on the heap. You can skip to the next section if you are already clear about Java reference types “ I have included the following paragraphs just to make the text more complete.

Like Java, and unlike C/C++, C# reference types are type-safe, meaning that it is impossible for a reference type variable to refer to some unallocated or random memory space which you can corrupt. Such type-safety means that a C# application cannot corrupt memory which has not been allocated for that application running on the Windows operating system (which supports multi-programming). The only way a C# program can access memory locations directly is via pointer operations in unsafe codes.

Reference types may be:

  • class type

  • interface type

  • array type

  • delegate type.

Like Java reference types, C# reference types can be either:

  • referring to an instance of the type or subtype stored on the heap; [2] or

    [2] C++ developers: C# no longer allows you to choose if you want your object to be created on the stack or heap. All C# objects are created on the heap with the new keyword.

  • null .

Reference types store references to their objects. With reference types, you can have two reference type variables referring to the same object on the heap, so that performing operations on one variable will affect the object referenced by the other variable (since they are referring to the same object). The code below shows an example of this scenario.

 1: using System;  2:  3: public class Test{  4:   public int i=0;  5:  6:   public static void Main(){  7:     Test t1 = new Test();  8:     Test t2 = new Test();  9:     t1.i = 1; 10:     t2.i = 2; 11:     Console.WriteLine("t1.i is " + t1.i); 12:     Console.WriteLine("t2.i is " + t2.i); 13: 14:     Console.WriteLine(" --------- "); 15: 16:     Test t3 = new Test(); 17:     Test t4 = t3; 18:     t3.i = 1; 19:     t4.i = 2; 20:     Console.WriteLine("t3.i is " + t3.i); 21:     Console.WriteLine("t4.i is " + t4.i); 22:   } 23: } 

Output:

 c:\expt>test t1.i is 1 t2.i is 2 --------- t3.i is 2 t4.i is 2 

In the example above, reference types t3 and t4 refer to the same object due to the assignment on line 17. Hence changing t3 's i value will also result in t4 's i being changed. Figure 9.2 shows a representation of this scenario.

Figure 9.2. Only three Test objects are actually created on the heap.

graphics/09fig02.gif



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net