How Objects are Created


In the preceding programs, the following line was used to declare an object of type Building:

 Building house = new Building();

This declaration performs two functions. First, it declares a variable called house of the class type Building. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, the declaration creates an actual, physical copy of the object and assigns to house a reference to that object. This is done by using the new operator. Thus, after the line executes, house refers to an object of type Building.

The new operator dynamically allocates (that is, allocates at runtime) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in a variable. Thus, in C#, all class objects must be dynamically allocated.

The two steps combined in the preceding statement can be rewritten like this to show each step individually:

 Building house; // declare reference to object house = new Building(); // allocate a Building object

The first line declares house as a reference to an object of type Building. Thus, house is a variable that can refer to an object, but it is not an object, itself. The next line creates a new Building object and assigns a reference to it to house. Now, house is linked with an object.

The fact that class objects are accessed through a reference explains why classes are called reference types. The key difference between value types and reference types is what a variable of each type means. For a variable of a value type, the variable, itself, contains the value. For example, given

 int x; x = 10;

x contains the value 10 because x is a variable of type int, which is a value type. However, in the case of

 Building house = new Building();

house does not, itself, contain the object. Instead, it contains a reference to the object.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net