VS debug issue, who can help me to explain this below?

后端 未结 1 976
天命终不由人
天命终不由人 2020-12-30 11:07

A piece of C# code

var isTrue = (new List{1,2,3} is IEnumerable);


I got result false in code executi

1条回答
  •  离开以前
    2020-12-30 11:44

    This is not a complete answer (I don't know the reasons why this bug is cropping up), but it sheds some light on the erratic behaviour of the debugger which is obviously buggy.

    First and foremost: C# disallows (and AFAIK, the CLR too) type variance involvig value types; variance is only allowed if there is an identity preserving conversion between the involved types, otherwise it will fail (there is no identity preserving conversion for value types):

    object[] oo = new int[] {1, 2, 3}; //will fail
    IEnumerable oo = new int[] {1, 2, 3}; //will fail
    
    
    

    The debugger's immediate window is obviously wrong, new List { 1, 2, 3 } is IEnumerable should return false as the runtime does. Why is it returning true? Because there's a bug, period.

    What makes it even more bewildering is the fact that new int[] { 1, 2, 3 } is IEnumerable will correclty return false when int[] is implicitly convertible to IEnumerable same as List.

    The only reason I find for the latter correct behavior is that the compiler already flags that expression as always false with a warning and therefore the way the compiler analyzes the array scenario is different from any other IEnumerable.

    0 讨论(0)
    提交回复
    热议问题