This chapter provided an overview of .NET, explained how to start a new project, and introduced some of the major features of C#Builder.
Chapter 2. C# Basics
Value Types and Reference Types
To keep track of what is happening in a C# program, it is important to understand what value types and reference types are and the differences between them. You will also need to know when to create each type and why, which helps in creating well-designed, efficient, and
is a type that is allocated on the managed heap. The reason it is called a reference type is that the
are allocated on the stack. They are named as such because they hold their actual value on the stack. When you copy one value type to another, the value is
Why value types and reference types? In other languages, built-in types, such as int and float , are often handled in a different way than objects. They are not really objects, so the developer must write special code and wrappers to make them behave properly in an object-oriented environment. In C#, many of the built-in types are value types, which allow them to be used in the same way that other objects are used. Also, because built-in types require special optimizations they must be handled by the system in a way that is efficient. Creating the concept of a value type enables C# to bring together the two goals of having object-oriented built-in types without sacrificing efficiency. By creating the concept of a value type, built-in types such as int and float may be worked with in a program the same as reference types, which are objects.
The C# language implements a concept known as
Type System Unification
, in which everything is
This automatic process of converting value types to objects is called
. Converting an object that has been boxed back to a value type variable is called
. The benefits of this can be seen when working with an
, or other Base Class Library (BCL) collection classes, which accept only
types. Value types assigned to the collection are automatically boxed when added and unboxed when retrieved. Be aware that overhead is associated with boxing and unboxing. Type system unification through boxing and unboxing supports object-oriented development and makes the developer's job easier. The following snippet
ArrayList myArrayList = new ArrayList(); int myInteger = 7; myArrayList.Add(myInteger); // myInteger is boxed myInteger = (int)myArrayList; // myInteger is unboxed
All C# types ultimately inherit from the
type. Built-in reference types inherit directly from
. However, value types inherit from
, which in
Figure 2.1. Value and reference type inheritance.