asp net 3.5unleashed

Page 300

Console.WriteLine(p);

// Displays (2, 2)

Object o = p; Console.WriteLine(o);

// Displays (2, 2)

((Point) o).Change(3, 3); // Changes temporary Point on sta ck! Console.WriteLine(o);

// Displays (2, 2)

} } Very simply, Main creates an instance of a Point value type on its stack and then changes its x and y fields to 1. The first call to WriteLine calls ToString on the unboxed Point, and "(1, 1)" is displayed, as expected. Then, p is used to call the Change method, which changes the values of p’s x and y fields on the stack to 2. The second call to WriteLine displays "(2, 2)", as expected. Now, p is boxed, and o refers to the boxed Point object. The third call to WriteLine again shows "(2, 2)", which is also expected. Finally, I want to call the Change method to update the fields in the boxed Point object. However, Object (the type of the variable o) doesn’t know anything about the Change method, so I must first cast o to a Point. Casting o to a Point unboxes o and copies the fields in the boxed Point to a temporary Point on the thread’s stack. The x and y fields of this temporary point are changed to 3 and 3, but the boxed Point isn’t affected by this call to Change. When WriteLine is called the second time, "(2, 2)" is displayed again. Many developers do not expect this. Some languages, such as C++ with Managed Extensions, let you change the fields in a boxed value type, but C# does not. However, you can fool C# into allowing this by using an interface. The following code is a modified version of the previous code: using System;

// Interface defining a Change method interface IChangeBoxedPoint { void Change(Int32 x, Int32 y); }

// Make the value type implement the interface. struct Point : IChangeBoxedPoint { public Int32 x, y;

public void Change(Int32 x, Int32 y) { this.x = x; this.y = y; }


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.