Free mag vol1 | Page 214

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II  Source Code The FunWithStructures project is located under the Chapter 4 subdirectory. Understanding Value Types and Reference Types  Note The following discussion of value types and reference types assumes that you have a background in object-oriented programming. If this is not the case, you might want to skip to the final section in this chapter, “Understanding C# Nullable Types,” and return to this section after you have read Chapters 5 and 6. Unlike arrays, strings, or enumerations, C# structures do not have an identically named representation in the .NET library (that is, there is no System.Structure class), but are implicitly derived from System.ValueType. Simply put, the role of System.ValueType is to ensure that the derived type (e.g., any structure) is allocated on the stack, rather than the garbage-collected heap. Simply put, data allocated on the stack can be created and destroyed very quickly, as its lifetime is determined by the defining scope. Heap allocated data, on the other hand, is monitored by the .NET garbage collector, and has a lifetime that is determined by a large number of factors, which will be examined in Chapter 13. Functionally, the only purpose of System.ValueType is to override the virtual methods defined by System.Object to use value-based, versus reference-based, semantics. As you might know, overriding is the process of changing the implementation of a virtual (or possibly abstract) method defined within a base class. The base class of ValueType is System.Object. In fact, the instance methods defined by System.ValueType are identical to those of System.Object: // Structures and enumerations implicitly extend System.ValueType. public abstract class ValueType : object { public virtual bool Equals(object obj); public virtual int GetHashCode(); public Type GetType(); public virtual string ToString(); } Given the fact that value types are using value-based semantics, the lifetime of a structure (which includes all numerical data types [int, float], as well as any enum or structure) is very predictable. When a structure variable falls out of the defining scope, it is removed from memory immediately: // Local structures are popped off // the stack when a method returns. static void LocalValueTypes() { // Recall! "int" is really a System.Int32 structure. int i = 0; // Recall! Point is a structure type. Point p = new Point(); } // "i" and "p" popped off the stack here! 149