Essential C# Simulating C Unions with C# Structs  Suggest an edit

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


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.

Table Of Contents
22 Enum
107 Stream
108 Timers
138 Simulating C Unions with C# Structs
  ↑ ↓ to navigate     ↵ to select     Esc to close