asp net 3.5unleashed

Page 165

public Point(Int32 x, Int32 y) { this.x = x; this.y = y; } } class Rectangle { public Point topLeft, bottomRight; public Rectangle() { // In C#, new on a value type just lets the constructor // initialize the already allocated value type’s memory. topLeft = new Point(1, 2); bottomRight = new Point(100, 200); } } A value type’s instance constructor is executed only when explicitly called. So if Rectangle’s constructor didn’t initialize its topLeft and bottomRight fields using the new operator to call Point’s constructor, the x and y fields in both Point fields would be 0. In the Point value type defined earlier, no default parameterless constructor is defined. However, let’s rewrite that code as follows:

struct Point { public Int32 x, y; public Point() { x = y = 5; } } class Rectangle { public Point topLeft, bottomRight; public Rectangle() { } } Now when a new Rectangle is constructed, what do you think the x and y fields in the two Point fields, topLeft and bottomRight, would be initialized to: 0 or 5? (Hint: This is trick question.) Many developers (especially those with a C++ background) would expect the C# compiler to emit code in Rectangle’s constructor that automatically calls Point’s default parameterless constructor for the Rectangle’s two fields. However, to improve the run-time performance of the application, the C# compiler doesn’t automatically emit this code. In fact, many compilers will never emit code to call a value type’s default constructor automatically, even if the value type offers a parameterless constructor. To have a value type’s parameterless constructor execute, the developer must add explicit code to call a value type’s constructor.


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