0

Debugging some code I came across an "is IEnumerable" comparison, which confusingly evaluates to false in code but true in the Immediate Window.

I wonder if anyone can shed light to why this would happen?

Example:

public enum Fruit
{
    Apples,
    Strawberries
}

public void SomeMethod()
{
    object myObj = new Fruit[] { Fruit.Apples, Fruit.Strawberries };

    bool isListOfEnums = myObj is IEnumerable<Fruit>; // True

    isListOfEnums = myObj is IEnumerable<Enum>; // False in code, but True in Immediate Window when debugged
}

(Immediate Window)

? myObj is IEnumerable<Enum>    
true
mhapps
  • 1,023
  • 8
  • 15

2 Answers2

3

It's a quirk of the intermediate window, basically. There are some pieces of code which evaluate differently there - it's one reason I generally prefer not to use the intermediate window.

An IEnumerable<Fruit> isn't an IEnumerable<Enum>. Each element of the latter would be a reference, as Enum is a reference type (just like ValueType is - I know, it's confusing) whereas each element of an IEnumerable<Fruit> is a Fruit value (not a reference).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon, watches also seem to be the same as the Immediate Window in this situation, guess I can no longer trust either. – mhapps Aug 01 '17 at 09:26
-1

Try quick watch to see the changes in the value of isListOfEnums. Or you can check its value multiple times in immediate window. You'll see it is being evaluated correctly. This is what I got and think working properly:-

?isListOfEnums
false
?isListOfEnums
true
?isListOfEnums
false
  • when public void SomeMethod() is invoked, value of isListOfEnums is false.
  • after myObj is IEnumerable<Fruit>; is evaluated, it becomes true.
  • after myObj is IEnumerable<Enum>; is evaluated, it beomes false again.