Saturday, February 1, 2025

Struct Vs Union in c#

In C#, both struct and union are used to create value types, but they are different significantly in memory allocation and usage. ________________________________________ 
1. struct in C# A struct in C# is a value type that contains multiple fields, where each field gets its own memory space. Structs are useful for representing small data structures that do not require reference semantics. 
Memory Allocation in struct Each field inside the struct has its own memory. The size of a struct is the sum of its field sizes (considering padding and alignment). 
Example of struct

Code Snippet

Memory Layout 
Field Type Size Id int 4 bytes Salary double 8 bytes Total 12 bytes (or more with padding) 
When to Use struct? 
✔️ Small, lightweight data structures 
✔️ When no need for inheritance 
✔️ When working with performance-sensitive applications (to avoid heap allocations) ________________________________________
  2. union in C# (Using StructLayout and FieldOffset) C# does not have a direct union like C/C++, but you can create a union-like structure using [StructLayout(LayoutKind.Explicit)] and [FieldOffset] attributes.
  How Does a union Work? 
• All fields share the same memory. 
• The size of the union is equal to the size of the largest field.
 • Writing to one field overwrites the other. Example of union in C#

Code Snippet

Output (may vary due to memory representation) 

intValue: 100, floatValue: 1.401298E-43, charValue: d

intValue: 1091567616, floatValue: 9.5, charValue: e

intValue: 65, floatValue: 9.10844E-44, charValue: A


     Why does this happen?
·        When intValue = 100, the same memory is interpreted as a float and a char.
·        When floatValue = 9.5f, the same memory gets rewritten.
·        When charValue = 'A', it affects the integer and float values.
Memory Layout of a union

Field

Type

Size (bytes)

intValue

int

4

floatValue

float

4 (shared)

charValue

char

2 (shared within 4 bytes)

Total Memory Used

4 bytes (size of the largest field)

When to Use a union?
✔️ Memory-efficient storage (especially useful for low-level programming)
✔️ Interop with unmanaged C/C++ code (e.g., working with hardware, binary data)
✔️ Working with bitwise operations
🚨 Caution: Accessing a different field than the last written one may produce undefined behavior.
🚀 Key Differences Between struct and union in C#

Feature

struct

union (via FieldOffset)

Memory Allocation

Each field gets separate memory

All fields share the same memory

Size

Sum of all field sizes (considering alignment)

Size of the largest field

Usage

When fields hold independent values

When only one field is used at a time

Performance

Faster but consumes more memory

Memory-efficient but risky

Common Use Cases

Small objects, lightweight data storage

Interoperability with unmanaged code, memory optimization


Conclusion
·    Use struct when you need a lightweight data type where each field has its own storage.
·   Use union (via StructLayout + FieldOffset) when you need memory-efficient structures where fields share the same memory.



No comments:

Post a Comment

How to Do Cross-Browser Testing on Windows — Including Safari via Playwright

To test follow few steps: Step 1. Install node Step 2. create Folder and run these commands commands Copy Code ...