You can use the new Span<T>
and MemoryMarshal
types to do this.
Note that this is only available with recent versions of C#, and you have to use a NuGet package to provide the library at the moment, but that will change.
So for example to "cast" a char array to a short array, you can write code like this:
var charArray = new char[100];
Span<short> shortArray = MemoryMarshal.Cast<char, short>(charArray);
charArray[0] = 'X';
Console.WriteLine(charArray[0]); // Prints 'X'
++shortArray[0];
Console.WriteLine(charArray[0]); // Prints 'Y'
This approach is documented and does not make any copies of any data - and it's also extremely performant (by design).
Note that this also works with structs:
struct Test
{
public int X;
public int Y;
public override string ToString()
{
return $"X={X}, Y={Y}";
}
}
...
var testArray = new Test[100];
Span<long> longArray = MemoryMarshal.Cast<Test, long>(testArray);
testArray[0].X = 1;
testArray[0].Y = 2;
Console.WriteLine(testArray[0]); // Prints X=1, Y=2
longArray[0] = 0x0000000300000004;
Console.WriteLine(testArray[0]); // Prints X=4, Y=3
Also note that this allows you to do some suspect things, like this:
struct Test1
{
public int X;
public int Y;
public override string ToString()
{
return $"X={X}, Y={Y}";
}
}
struct Test2
{
public int X;
public int Y;
public int Z;
public override string ToString()
{
return $"X={X}, Y={Y}, Z={Z}";
}
}
...
var test1 = new Test1[100];
Span<Test2> test2 = MemoryMarshal.Cast<Test1, Test2>(test1);
test1[1].X = 1;
test1[1].Y = 2;
Console.WriteLine(test1[1]); // Prints X=1, Y=2
test2[0].Z = 10; // Actually sets test1[1].X.
Console.WriteLine(test1[1]); // Prints X=10, Y=2