I have an array of shorts:
short[] data;
And I have a function that writes bytes to a file:
void Write(byte[] data);
I do not control this function and cannot change it. Is there a way to write my array of shorts without making a redundant copy first to convert it to bytes?
Something like that: Write((byte[])data);
I do not care about endianness. I want memory representation of shorts written to a file in whatever the machine representation of short is. I understand this kind of cast cannot work for any non-POD type that contains references, but shorts should be perfectly convertible. The cast should result in a byte array twice the size that points to the same memory.
If this is impossible in C#, is there anything in CLR that makes this impossible, or is it just C# limitation?
Array.ConvertAll(array, item => (byte)item)is as optimal as you're going to get. This ensures that the array is iterated over only once. Let the compiler deal with the performance implications. If you cared about this kind of low level stuff, you wouldn't be writing in C#.