In C#/.NET why is sbyte[] the same as byte[] except that it's not?

前端 未结 4 854
悲哀的现实
悲哀的现实 2020-12-08 04:05

I just observed a weird phenomenon in C#/.NET.

I created this minimal example to demonstrate:

if (new sbyte[5] is byte[])
{
 throw new ApplicationExc         


        
4条回答
  •  Happy的楠姐
    2020-12-08 04:39

    The CLR rules of casting specify that this is possible. The C# rules say it is not possible. The C# team consciously decided that they would tolerate this deviation from the spec for various reasons.

    Why does the CLR allow this? Probably because they can conveniently implement it. byte and sbyte have the same binary representation so you can "treat" a byte[] as an sbyte[] without violating memory safety.

    The same trick works for other primitive types with the same memory layout.

提交回复
热议问题