Reference Variables and Assignment


In an assignment operation, reference variables act differently than do variables of a value type, such as int. When you assign one value type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. When you assign an object reference variable to another, the situation is a bit more complicated because you are changing the object to which the reference variable refers. The effect of this difference can cause some counterintuitive results. For example, consider the following fragment:

 Building house1 = new Building(); Building house2 = house1;

At first glance, it is easy to think that house1 and house2 refer to different objects, but this is not the case. Instead, house1 and house2 will both refer to the same object. The assignment of house1 to house2 simply makes house2 refer to the same object as does house1. Thus, the object can be acted upon by either house1 or house2. For example, after the assignment

 house1.area = 2600;

executes, both of these WriteLine( ) statements

 Console.WriteLine(house1.area); Console.WriteLine(house2.area);

display the same value: 2600.

Although house1 and house2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to house2 simply changes the object to which house2 refers. For example:

 Building house1 = new Building(); Building house2 = house1; Building house3 = new Building(); house2 = house3; // now house2 and house3 refer to the same object.

After this sequence executes, house2 refers to the same object as house3. The object referred to by house1 is unchanged.




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