I want to convert a multidimensional array of int[,]
to an array of ushort[,]
and if possible without looping over each dimension.
I found a post where object[,]
is converted to double[,]
by using Array.Copy
. Unfortunately this only works because the objects are allready of type double
. Is there any chance to achieve a similar result for converting int to ushort (assuming it always fits)?
var input = new [,]
{
{1,1,1},
{2,2,2},
{3,3,3}
};
var output = new ushort[3, 3];
// Convert
Array.Copy(input, output, input.Length);
The above code compiles, but fails on execution because it can not convert from int
to ushort
. I know why this happens, I just want to tell .NET that it should just convert.
As I said I know the easiest solution are two loops. I am just curious if there is an alternative.
Conclusion: Unfortunately there is no fast and built-in way to do this. Therefore I recommend the obvious and readable solution of going for the double loop unless you really need lightning speed fast conversion.
for(var i=0; i<input.GetLength(0); i++)
for(var j=0; j<input.GetLength(1); j++)
output[i,j] = (ushort)input[i,j];
However this is not the accepted solution since for my personal interest I was asking for the fastest alternative and that is, as expected, and evil and unsafe pointer conversion.