Chapter 18 Unsafe code
Structs are similar to classes in that they represent data structures that can contain data members and function members. However, unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data, the latter known as an 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. Key to these data structures is that they have few data members, that they do not require use of inheritance or referential identity, and that they can be conveniently implemented using value semantics where assignment copies the value instead of the reference.
As described in §4.1.4, the simple types provided by C#, such as int, double, and bool, are in fact all struct types. Just as these predefined types are structs, it is also possible to use structs and operator overloading to implement new “primitive” types in the C# language. Two examples of such types are given at the end of this chapter (§11.4).
11.1 Struct declarations
A struct-declaration is a type-declaration (§9.5) that declares a new struct:
struct-declaration: attributesopt struct-modifiersopt struct identifier struct-interfacesopt struct-body ;opt
A struct-declaration consists of an optional set of attributes (§17), followed by an optional set of struct-modifiers (§11.1.1), followed by the keyword struct and an identifier that names the struct, followed by an optional struct-interfaces specification (§11.1.2), followed by a struct-body (§11.1.3), optionally followed by a semicolon.
11.1.1 Struct modifiers
A struct-declaration may optionally include a sequence of struct modifiers:
struct-modifiers: struct-modifier struct-modifiers struct-modifier
struct-modifier: new public protected internal private
It is a compile-time error for the same modifier to appear multiple times in a struct declaration.
The modifiers of a struct declaration have the same meaning as those of a class declaration (§10.1.1).
11.1.2 Struct interfaces
A struct declaration may include a struct-interfaces specification, in which case the struct is said to implement the given interface types.
Copyright Microsoft Corporation 1999-2003. All Rights Reserved.260