0

I have 2 questions about the following code:

 IEnumerable<int> arr = new int[] { 2, 17, 4, 6 };
 Console.WriteLine(arr.GetType());

The output is:

 System.Int32[]
  1. What is the class of "arr" variable? is it Array class? Does Array class equal every XXX[]?
  2. if arr is from Array class, how is it successfully converted to IEnumerable(int) interface? I see that Array implements only IEnumerable, but not IEnumerable(T)

Thanks

Jaxx
  • 1,355
  • 2
  • 11
  • 19
  • There are plenty of questions why cast does not change type of object and how array implements enumerable... – Alexei Levenkov Nov 16 '17 at 23:00
  • Look at `new int[]`. Obviously, *arr* is an instance of `int[]`, which is special "auto-generated" type which implements these interfaces thanks to the CLR. – IS4 Nov 16 '17 at 23:00
  • @Dave That's not true. If `Car : Vehicule` and `Bus : Vehicule`, a `Bus` cannot be stored as a `Car` – Arthur Rey Nov 16 '17 at 23:02
  • Looks very similiar to https://stackoverflow.com/questions/2773740/why-do-arrays-in-net-only-implement-ienumerable-and-not-ienumerablet – eisenpony Nov 16 '17 at 23:05
  • @IllidanS4, does this special generated type "int[]" inherit from Array? – Jaxx Nov 17 '17 at 07:07
  • @Jaxx Yes, it can be confirmed with reflection or the fact that you can cast it to *Array*. – IS4 Nov 17 '17 at 20:40

1 Answers1

0
  1. The type is System.Int32[]. Yes, this is an instance of the Array class. Edit: See Hans' comment below.
  2. From the documentation of Array Class: https://msdn.microsoft.com/en-us/library/system.array.aspx

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class

eisenpony
  • 565
  • 4
  • 10
  • 1
    The Array class is abstract, you can never create an instance of it. Review Type.MakeArrayType() to get insight in how the CLR dynamically creates array types. – Hans Passant Nov 16 '17 at 23:19