Skip to content

Usage of StructLayout(LayoutKind.Explicit) #191

@HeinzKessler

Description

@HeinzKessler

Suggestion:

A difference between OneOf and C/C++ unions is that with C/C++, a union only uses as much memory as the largest possible field, because all fields overlap in memory.
Since OneOf makes sure that always only one of these fields is valid and in use, such an overlapping structure layout could also be beneficial for OneOf, if memory consumption is a concern.

.Net gives the opportunity to specify the memory layout for the fields of a class or struct. With the StructLayout(LayoutKind.Explicit), all fields could have the same memory address, like in C/C++ unions, by setting FieldOffset of 0, for all of them.

See the documentation of the feature here:
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8

For the fields to overlap in memory, FieldOffset must be set 0 for all fields in the example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions