Skip to main content

Command Palette

Search for a command to run...

Interchangeability of Integral Type Arrays

Updated
1 min read

In .NET, an array of a simple integral type can be cast to an array of another integral type, provided they have the same element size. This is possible because the CLR treats these arrays as having a compatible memory layout.

int[] arrayOfInts = new int[5];
arrayOfInts[0] = -12;

// Cast via object or Array to bypass the compiler check
uint[] arrayOfUints = (uint[])(object)arrayOfInts;

Console.WriteLine(arrayOfUints[0]); // Output: 4294967284 (binary representation of -12)

Key Points:

  • Size Identity: This works between types of the same bit-width, such as int[] and uint[], or short[] and ushort[].

  • Pointer Types: It also applies to IntPtr[] and UIntPtr[].

  • Platform Dependency: You can cast IntPtr[] to int[] on x86, or to long[] on x64, because their sizes match on those specific architectures.

  • Why it works: The CLR does not perform a conversion of the data; it simply reinterprets the existing memory. This is similar to a reinterpret_cast in C++.

Note: While powerful for high-performance scenarios, use this with caution as it bypasses the type safety usually expected in C#.