I've got a function which fills an array of type sbyte[], and I need to pass this array to another function which accepts a parameter or type byte[].
Can I convert it nicely and quickly, without copying all the data or using unsafe
magic?
I've got a function which fills an array of type sbyte[], and I need to pass this array to another function which accepts a parameter or type byte[].
Can I convert it nicely and quickly, without copying all the data or using unsafe
magic?
You will have to copy the data (only reference-type arrays are covariant) - but we can try to do it efficiently; Buffer.BlockCopy
seems to work:
sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
If it was a reference-type, you can just cast the reference without duplicating the array:
Foo[] arr = { new Foo(), new Foo() };
IFoo[] iarr = (IFoo[])arr;
Console.WriteLine(ReferenceEquals(arr, iarr)); // true
If you are using .NET 3.5+, you can use the following:
byte[] dest = Array.ConvertAll(sbyteArray, (a) => (byte)a);
Which is, I guess effectively copying all the data.
Note this function is also in .NET 2.0, but you'd have to use an anonymous method instead.
You may look at hacks in next thread: C# unsafe value type array to byte array conversions.