The following code and Figure 5-2 demonstrate how reference types and value types differ:
// Reference type (because of 'class')
class SomeRef { public Int32 x; }
// Value type (because of 'struct')
struct SomeVal { public Int32 x; }
static void ValueTypeDemo() {
SomeRef r1 = new SomeRef(); // Allocated in heap
SomeVal v1 = new SomeVal(); // Allocated on stack
r1.x = 5; // Pointer dereference
v1.x = 5; // Changed on stack
Console.WriteLine(r1.x); // Displays "5"
Console.WriteLine(v1.x); // Also displays "5"
// The left side of Figure 5-2 reflects the situation
// after the lines above have executed.
SomeRef r2 = r1; // Copies reference (pointer) only
SomeVal v2 = v1; // Allocate on stack & copies members
r1.x = 8; // Changes r1.x and r2.x
v1.x = 9; // Changes v1.x, not v2.x
Console.WriteLine(r1.x); // Displays "8"
Console.WriteLine(r2.x); // Displays "8"
Console.WriteLine(v1.x); // Displays "9"
Console.WriteLine(v2.x); // Displays "5"
// The right side of Figure 5-2 reflects the situation
// after ALL of the lines above have executed.
}
You should declare a type as a value type if one of the following statements is true:
1. Instances o fthe type are small (approximately 16 bytes or less).
2. Instances of the type are large(greater than 16 bytes) and are not passed as method paramerter
or returned from mehtods.
Value type objects have tow representation : an Unboxed from and a boxed from .
Reference types are always in a boxed from.
** Referenece type variables contain the memory address of objects in the heap.
** when you assign a value type variable ot antoher value type variable, a field by field copy is made.
when you assign a reference type variable to another reference type variable, only the memory address is copied.
The value type instance doesn't receive a notification ( via a Finalize mehtod) when the memory is reclaimed.
No comments:
Post a Comment