3

I'm having trouble explaining the following behaviour in C#

class A {    }
class Program
{
    static void Main(string[] args)
    {
        IEnumerable<int> a = new List<int> { 1, 2, 3 };
        IEnumerable<char> b = "sdf";
        IEnumerable<A> c = new List<A> { new A() };

        Console.WriteLine(a is IEnumerable<object>); //false
        Console.WriteLine(b is IEnumerable<object>); //false 
        Console.WriteLine(c is IEnumerable<object>); //true
    }
}

Why is only List of custom types recognized as IEnumerable< object>

Esben Skov Pedersen
  • 4,437
  • 2
  • 32
  • 46
  • Probably because only A is a reference type, int and char are a struct – Kamil T Jun 22 '16 at 06:37
  • 1
    int and char are **not** inherited from object. You can assign them to object because .net will automatic wrap them to a boxed object containing the value. Read the docs https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx – Sir Rufo Jun 22 '16 at 06:42
  • 3
    @SirRufo: `int` and `char` *are* inherited from `object` (e.g., `System.Object ` -> `System.ValueType` -> `System.Int32`). At least, while we're talking about .NET. Stop this madness, please. This is variance issue for value-types. – Dennis Jun 22 '16 at 06:44
  • @Dennis Then please talk to Microsoft that the docs are totally wrong regarding boxing (see my link). Until that I take the docs as true – Sir Rufo Jun 22 '16 at 06:45
  • @SirRufo: you're confusing inheritance and memory representation/memory location. – Dennis Jun 22 '16 at 06:46
  • @Dennis I am as confused as John Skeet - I can live with that :o) – Sir Rufo Jun 22 '16 at 06:51
  • This answer linked from the linked answer from Eric Lippert explained it nicely. http://stackoverflow.com/a/4098434/170196 – Esben Skov Pedersen Jun 22 '16 at 06:52
  • @SirRufo: could you post JS citation, where he claims, that `int` (or `char`) isn't inherited from `object`? – Dennis Jun 22 '16 at 06:53
  • @Dennis See the duplicate question link and the accepted answer – Sir Rufo Jun 22 '16 at 06:54
  • 2
    @SirRufo: where's citation about *inheritance*? Could you post it? :) We need boxing, because reference types and value types have different memory representation. Boxing isn't related to inheritance hierarchy. All value types (including `int`, `char`, etc) are implicitly inherited from `System.ValueType`, which, in turn, is inherited from `System.Object`. – Dennis Jun 22 '16 at 06:56
  • @Dennis You are right (I just read the articles from Eric Lippert) with the inheritence – Sir Rufo Jun 22 '16 at 07:09

0 Answers0