X hits on this document





278 / 396

Chapter ‎18   Unsafe code

struct Point { int x, y;

public int X { set { x = value; } }

public int Y { set { y = value; } }

public Point(int x, int y) { X = x;// error, this is not yet definitely assigned Y = y;// error, this is not yet definitely assigned } }

No instance member function (including the set accessors for the properties X and Y) can be called until all fields of the struct being constructed have been definitely assigned. Note, however, that if Point were a class instead of a struct, the instance constructor implementation would be permitted.

11.3.9 Destructors

A struct is not permitted to declare a destructor.

11.3.10 Static constructors

Static constructors for structs follow most of the same rules as for classes. The execution of a static constructor for a struct is triggered by the first of the following events to occur within an application domain:

An instance member of the struct is referenced.

A static member of the struct is referenced.

An explicitly declared constructor of the struct is called.

The creation of default values (§‎11.3.4) of struct types does not trigger the static constructor. (An example of this is the initial value of elements in an array.)

11.4 Struct examples

The following shows two significant examples of using struct types to create types that can be used similarly to the built-in types of the language, but with modified semantics.

11.4.1 Database integer type

The DBInt struct below implements an integer type that can represent the complete set of values of the int type, plus an additional state that indicates an unknown value. A type with these characteristics is commonly used in databases.

using System;

public struct DBInt { // The Null member represents an unknown DBInt value.

public static readonly DBInt Null = new DBInt();

// When the defined field is true, this DBInt represents a known value // which is stored in the value field. When the defined field is false, // this DBInt represents an unknown value, and the value field is 0.

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

Document info
Document views903
Page views903
Page last viewedTue Dec 06 19:13:47 UTC 2016