Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

debugging

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.

like image 427
Raymond He Avatar asked Nov 30 '17 07:11

Raymond He


People also ask

How debugging is done in VS code?

To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut Ctrl+Shift+D. The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.


1 Answers

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.

like image 118
InBetween Avatar answered Sep 18 '22 12:09

InBetween