Understanding Value Types and Reference Types

Recall from our discussion of arrays that you must use the new keyword to create the array. This requirement differs from the types that have been discussed so far. When you work with code that uses int or long variables, for instance, you can use the variable without calling new:

int IntegerVariable;

IntegerVariable = 12345;

Why are the arrays different? Why is new required when creating an array? The answer lies in the difference between value types and reference types.

With a value type, the variable holds the value of the variable. With a reference type, the variable holds a reference to a value stored elsewhere in memory. You can think of a reference as a variable that points to another piece of memory. Figure 3-2 shows the difference.

ml InleyerVariatjle 123

long I orngVariabk? J56

itoutjle P ArfyyOfDwWes

0.0 | C O

0.0 | 0.Û | 0.0

Figure 3-2: Value types hold data. Reference types hold references to data placed elsewhere in memory.

Each of the types discussed until this point is a value type. The variables provide enough storage for the values that they can hold, and you don't call new to create space for their values. Arrays of value types and objects are reference types. Their values are held elsewhere in memory, and you need to use the new keyword to create enough space for their data.

Although you need to use the new keyword to create memory space for a reference type, you don't need to write any code to delete the memory when you are finished using the variable. The CLR contains a mechanism called a garbage collector, which performs the task of releasing unused memory. The CLR runs the garbage collector while your C# application runs. The garbage collector searches through your program looking for memory that is no longer being used by any of your variables. It is the job of the garbage collector to free the unused memory automatically.

0 0

Post a comment