Records (also called "Structures" or "Structs", in many other programming languages) are a lot like Classes except for two crucial differences:
- Records are value types, and stored on the stack, while classes are reference types, and stored in global memory.
- While they can have an ancestry hierarchy (i.e. a record type can decent from and extend another record), they do not support polymorphism, e.g., overriding virtual methods.
When using a record type, the value is stored on the stack (or when defined inside a different type, it is stored inline within the memory space of that type). Assigning a record from one variable to another creates a copy of the record, and making changes to on copy does not affect the other. For this reason, records are usually used to hold a small number of related values.
See Value Types vs. Reference Types) for more on stack- vs heap-baswed types.
On .NET, a
StructLayout Aspect can be used to change the size and alignment of a structure, which is useful when used in combination with P/Invoke calls to native platform APIs. Similarly, the
FieldOffset Aspect can be used to set the offset of individual fields within the record.
A record type is declared using the
record keyword, followed by zero or more member declaratins, and closed off with the
end keyword. An optional ancestor and/or a list of one of more interfaces to implement can be provided in parenthesis behind the
type Color = public record(IColor) public R, G, B, A: Byte; end;
Like all custom types, records can be nested in other types with
nested in syntax.
Records can define Invariants to help ensure a consistent state. Invariants are boolean expressions that will automatically be enforced by the compiler.
Note that invariants can only be effective for non-public fields, as access to public fields would bypass them. This makes invariants less useful for most typical records rthan they are for Classes.
Refer to the Nested Types topic for more details.
The visibility of a record type can be controlled by applying a Visibility Modifier on the declaration. The default visibility is
A number of other Type Modifiers can be applied to records: