Reputation: 127
A piece of C# code
var isTrue = (new List<int>{1,2,3} is IEnumerable<object>);
I got result false
in code execution,
but when I copy that code into WATCH window, the result is true
.
Upvotes: 9
Views: 153
Reputation: 32740
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<object> oo = new int[] {1, 2, 3}; //will fail
The debugger's immediate window is obviously wrong, new List<int> { 1, 2, 3 } is IEnumerable<object>
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<object>
will correclty return false
when int[]
is implicitly convertible to IEnumerable<int>
same as List<int>
.
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
.
Upvotes: 1