X hits on this document





38 / 396

Chapter ‎18   Unsafe code

class Test { static void Main() { List a = new List(); a.Add(1); a.Add(2); List b = new List(); b.Add(1); b.Add(2); Console.WriteLine(a == b);// Outputs "True" b.Add(3); Console.WriteLine(a == b);// Outputs "False" } }

The first Console.WriteLine outputs True because the two lists contain the same number of objects with the same values. Had List not defined operator ==, the first Console.WriteLine would have output False because a and b reference different List instances. Destructors

A destructor is a member that implements the actions required to destruct an instance of a class. Destructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be invoked explicitly. The destructor for an instance is invoked automatically during garbage collection.

The garbage collector is allowed wide latitude in deciding when to collect objects and run destructors. Specifically, the timing of destructor invocations is not deterministic, and destructors may be executed on any thread. For these and other reasons, classes should implement destructors only when no other solutions are feasible.

1.7 Structs

Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs. For example, the following program creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated—one for the array and one each for the 100 elements.

class Point { public int x, y;

public Point(int x, int y) { this.x = x; this.y = y; } }

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.25

Document info
Document views1460
Page views1460
Page last viewedTue Jan 24 07:52:19 UTC 2017