Value and Reference Types

Value type is a data type which are either built-in types, or structure(struct) or an enumeration(enum).When value-type instance are created, only a single space in memory is allocated to store the value.

Reference type are referred to as objects including Classes, Interfaces, Delegates, Instances arrays, and as well as the built in reference types. When reference types is created two spaces are allocated one for instance and another for its reference.

The runtime deals with the value types and reference types in two different ways.

theStruct myStruct1 = new theStruct();
myStruct1.X = 10;

//Struct is a value type,
//myStruct2 becomes an independent copy of myStruct1, with its own fields.
theStruct myStruct2 = myStruct1;
myStruct2.X = 20;
Console.WriteLine("myStruct1: {0}", myStruct1.X);
Console.WriteLine("myStruct2: {0}", myStruct2.X);

Output
 
myStruct1:10
myStruct2:20

Now Repeat the same with a reference type.

The output will be 20,20.

0 comments:

Post a Comment