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

前端 未结 4 866
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2020-12-08 04:29

    Here's a simpler example that shows the same issue:

    static void Main(string[] args)
    {
        bool a = ((object) new byte[0]) is sbyte[];
        bool b = (new byte[0]) is sbyte[];
    
        Console.WriteLine(a == b); // False
    }
    

    The inconsistency arises because the C# compiler decides that it knows the result of (new byte[0]) is sbyte[] at compile time, and just substitutes false. Perhaps it should really substitute true, to be more consistent with the CLR behaviour.

    As far as I can tell, it's only this little optimization that's inconsistent. It occurs only when both sides of the is expression are statically typed as an array whose element type is a signed or unsigned integer or an enum, and the sizes of the integers are the same.

    The good news is that while this might seem inconsistent, C# will always issue a warning when it substitutes false into such expressions – in practice, I think this might be more useful than quietly returning true.

提交回复
热议问题