Interchangeability of Integral Type Arrays
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[]anduint[], orshort[]andushort[].Pointer Types: It also applies to
IntPtr[]andUIntPtr[].Platform Dependency: You can cast
IntPtr[]toint[]on x86, or tolong[]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_castin C++.
Note: While powerful for high-performance scenarios, use this with caution as it bypasses the type safety usually expected in C#.




