Write signed byte array to a stream

I want to write signed byte array sbyte[] to a stream. I know that Stream.Write accepts only unsigned byte[], so I could convert sbyte[] to byte[] prior to passing it to the stream. But I really need to send the data as sbyte[]. Is there some way to do it? I found BinaryWriter.Write but is this equivalent to Stream.Write?

Jon Skeet
people
quotationmark

You can use the fact that the CLR allows you to convert between byte[] and sbyte[] "for free" even though C# doesn't:

sbyte[] data = ...;
byte[] equivalentData = (byte[]) (object) data;
// Then write equivalentData to the stream

Note that the cast to object is required first to "persuade" the C# compiler that the cast to byte[] might work. (The C# language believes that the two array types are completely incompatible.)

That way you don't need to create a copy of all the data - you're still passing the same reference to Stream.Write, it's just a matter of changing the "reference type".

people

See more on this question at Stackoverflow