2

In C# I'm getting some strange results when casting an object variable (which happens to hold an integer array) as an IEnumerable<object>.

object arr = new[] {1, 2, 3};
var tst1 = arr as IEnumerable<int>;
var tst2 = arr as IEnumerable<object>;

When this runs, the first cast succeeds, but the second fails. However, if I debug this code in Visual Studio and evaluate arr as IEnumerable<object> in the Immediate Window or Watch panes, the cast succeeds. So I have a few questions:

1) Why is the cast invalid?

2) Why is the debugger able to perform the cast?

Bonus Points:

-Does T[] really implement IEnumerable<T>? Is an int really an object?

-When casting to a type with a covariant generic argument, what types are valid for the instance?

Kyle McClellan
  • 664
  • 7
  • 23

0 Answers0