# Optional Structures

> A `struct` in eXtremeDB terminology, is a collection of data elements grouped together that can be designated as a field of a class. An `optional` declaration means that the field may or may not be actually stored in the database, the eXtremeDB runtime does not allocate memory for `optional struct` fields until the application explicitly assigns a value to the field. Actual data for `optional` structures are stored in the database only when a new transaction is committed. If the field is not stored, the runtime does not reserve (allocate) space for it within the data layout except a 2 or 4 byte reference address, and the associated get methods will return a null pointer (In the C API, `classname_fieldname_read_handle()` and `classname_fieldname_write_handle()` functions will return the error code `MCO_E_EMPTYOPTIONAL`).

> The memory allocation rules for a structure are the same as for all other fields - if a struct, included in a class, has dynamic fields then the class will be stored in tree-like memory layout. Otherwise the eXtremeDB runtime will store it as a fixed record. For an `optional struct` field, as for dynamic fields, eXtremeDB will always use a tree-like memory layout.

> To perform operations on `optional structs` the application uses the same APIs as for ordinary structs (in the C API classname_structname_read_handle() and classname_structname_write_handle() ). The only differences are the three following considerations:

> > 1. To allocate an `optional struct` it is necessary to write into it using the classname_structname_write_handle() function to obtain a write handle.

> > 2. The classname_structname_read_handle() API may return `MCO_E_EMPTYOPTIONAL` if the `optional struct` field was not yet allocated.

> > 3. Use the classname_fieldname_erase() API to de-allocate the optional struct.

> As for dynamic fields, the eXtremeDB runtime provides an internal mechanism for memory defragmentation and performs Automatic compaction which will reduce the `optional struct` size, but the tree-like memory layout overhead remains.