Free mag vol1 | Page 221

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II  Source Code The RefTypeValTypeParams project is located under the Chapter 4 subdirectory. Final Details Regarding Value Types and Reference Types To wrap up this topic, consider the information in Table 4-3, which summarizes the core distinctions between value types and reference types. Table 4-3. Value Types and Reference Types Comparison 156 Intriguing Question Value Type Reference Type Where are objects allocated? Allocated on the stack. Allocated on the managed heap. How is a variable represented? Value type variables are local copies. Reference type variables are pointing to the memory occupied by the allocated instance. What is the base type? Implicitly extends System.ValueType. Can derive from any other type (except System. ValueType), as long as that type is not “sealed” (more details on this in Chapter 6). Can this type function as a base to other types? No. Value types are always sealed and cannot be inherited from. Yes. If the type is not sealed, it may function as a base to other types. What is the default parameter passing behavior? Variables are passed by value (i.e., a copy of the variable is passed into the called function). For value types, the object is copied-by-value. For reference types, the reference is copied-by-value. Can this type override System.Object.Finalize()? No. Value types are never placed onto the heap and, therefore, do not need to be finalized. Yes, indirectly (more details on this in Chapter 13). Can I define constructors for this type? Yes, but the default constructor is reserved (i.e., your custom constructors must all have arguments). But, of course! When do variables of this type die? When they fall out of the defining scope. When the object is garbage collected.