Casting sbyte[] to bool[] and a char[] to short[]

  • A+
Category:Languages

Is there anyway to explicitly cast/coerce

  • sbyte[] or byte[] to a bool[]
  • char[] to a short[]/ushort[]

In CIL you regularly see something such as

stelem Type sbyte (ldloc pArray) ldc_i4 1 ldc_i4 0  

which is doing pArray[1] = true where pArray is a one-dimensional array of type bool[]. I want to replicate this in c# by doing

(sbyte[])pArray[1] = 1; 

Unfortunately this is not allowed by the C# compiler.


Undocumented trick, play at your own risk:

(shown for example here and in many other places)

[StructLayout(LayoutKind.Explicit)] public struct ConvSByteBool {     [FieldOffset(0)]     public sbyte[] In;     [FieldOffset(0)]     public bool[] Out; } 

and then:

var bytes = new sbyte[] { -2, -1, 0, 1, 2 }; var conv = new ConvSByteBool { In = bytes }.Out; bool b1 = conv[0]; // true bool b2 = conv[1]; // true bool b3 = conv[2]; // false bool b4 = conv[3]; // true bool b5 = conv[4]; // true 

Note that this trick is tottally incompatible with generics. No Conv<T, U>!

The trick works best when the size of the element in source and target is the same (sizeof(sbyte) == sizeof(bool)). Otherwise there are some limitations (described in the linked question above).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: