Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
547 18 Structs 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. Freedom of allocation The Standard states that value types "do not require heap allocation" but does not forbid it or recommend an alternative. However, it does specify the semantics of value types, such as copy-on-assignment. The most conventional choice for an implementation would be to use stack allocation for local variables and method parameters of value type, and indeed all implementations available at the time of writing do so. However, where should, for example, a static field of value type be stored? Stack allocation seems less suitable: Which stack frame would be used? It is left to the implementor to decide what is most appropriate on the target platform, and the two major implementations current at the time of writing have handled this differently. It is important to note that this implementa- tion choice does not impact the C# programmer and need be of no concern to him. "Heap" allocation required The freedom of allocation is curtailed in the presence of local variable capture by anonymous methods (§14.5.15.3.1). If a local variable is captured, its lifetime may have to be extended beyond that of the current method activation, and that usually precludes stack allocation. The standard approach is to "box" captured local variables into an instance, allocated on the heap, of a compiler-generated class.