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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any C# Language Question?