I need to convert an int[] array to a ushort[] array in order to use the method Array.Copy() from theses two types of array.
Which method should I use ?
On
The simple way to get a ushort array from an int array is:
public static void Main(string[] args)
{
int[] intArr = new int[5]{1,2,3,4,5}; // Creates an array of ints
ushort[] ushortArr = new ushort[5]; // Creates an array of ushorts
// Copy the int array to the ushort array
for(int i=0; i<intArr.Length; i++){
ushortArr[i] = (ushort)intArr[i];
}
// Prints the ushort array
foreach(ushort u in ushortArr){
Console.Write(u+", ");
}
}
The output of this program is:
1, 2, 3, 4, 5,
note: you need to make sure that the length of the ushort array is the same as the length of the int array.
I believe this is a very simple solution. I hope it helps :)
On
There are cleaner alternatives, but assuming you need to do somethng when an int can't be an unsigned short:
public ushort[] ToUnsignedShortArray(int[] intArray)
{
if (intArray == null)
{
return new ushort[0];
}
var shortArray = new ushort[intArray.Length];
for (var i = 0; i < intArray.Length; i++)
{
// add your logic for determining what to do if the value can't be an unsigned short
shortArray[i] = (ushort)intArray[i];
}
return shortArray;
}
The advantage of
Array.ConvertAllhere is that it right-sizes the target array from the outset, so it never allocates multiple arrays, and can be used conveniently.The
checkedhere causes theinttoushortconversion to throw an exception if an overflow is detected; this is not done by default.