How to use C# Structs to create a Union type Similar to C Unions

suggest change

Remarks

Union types are used in several languages, notably C-language, to contain several different types which can “overlap” in the same memory space. In other words, they might contain different fields all of which start at the same memory offset, even when they might have different lengths and types. This has the benefit of both saving memory, and doing automatic conversion.

Please, note the comments in the constructor of the Struct. The order in which the fields are initialized is extremely important. You want to first initialize all of the other fields and then set the value that you intend to change as the last statement. Because the fields overlap, the last value setup is the one that counts.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Simulating C Unions with C# Structs:
* How to use C# Structs to create a Union type Similar to C Unions

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
137 Simulating C Unions with C# Structs
147 C# Script