I have an extension method that converts an array of numeric type A to an array of numeric type B
public static T2[] ConvertTo<T1, T2>(this T1[] buffer)
{
var bufferNumBytes = buffer.Length * Marshal.SizeOf(default(T1));
var targetElementNumBytes = Marshal.SizeOf(default(T2));
if (bufferNumBytes % targetElementNumBytes != 0)
{
throw new ArgumentException($"Array must have multiple of {targetElementNumBytes} bytes, has {bufferNumBytes} bytes instead", nameof(buffer));
}
var res = new T2[bufferNumBytes / targetElementNumBytes];
Buffer.BlockCopy(buffer, 0, res, 0, bufferNumBytes);
return res;
}
I can call it like
var b = new ushort[] { 1, 256 };
var us = b.ConvertTo<ushort, byte>();
Assert.That(us[0], Is.EqualTo(1));
Assert.That(us[1], Is.EqualTo(0));
Assert.That(us[2], Is.EqualTo(0));
Assert.That(us[3], Is.EqualTo(1));
However, that T1 paramter seems redundant, but I don´t know how to get rid of it. One workaround would be more generic extension methods
public static T1[] ConvertTo<T1>(this byte[] buffer)
{
return buffer.ConvertTo<byte, T1>();
}
public static T1[] ConvertTo<T1>(this sbyte[] buffer)
{
return buffer.ConvertTo<sbyte, T1>();
}
public static T1[] ConvertTo<T1>(this ushort[] buffer)
{
return buffer.ConvertTo<ushort, T1>();
}
...
But I would prefer a simpler approach with just one parameter (target type) and the compiler infering the type of buffer by itself.