0

I am able to call ToArray() method of List<T> class from a reference of IList<T> interface, just by including the line using System.Linq. But without the Linq namespace, the code gave an error saying, "no such method in IList interface".

Using C# with .NET Core.

IList<int> l = new List<int>();
...

int[] arr = (int[])l.ToArray(typeof(int));
mrJ
  • 1
  • 1

2 Answers2

0

I don't find a ToArray() that takes parameters.

This code :

int[] arr =l.ToArray();
int[] arr2 = (int[])l.ToArray();

Is equivalent to this :

int[] array = Enumerable.ToArray(l);
int[] array2 = Enumerable.ToArray(l);

IL code: intersting part at IL_0008 and IL_000f


IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call !!0[] [System.Core]System.Linq.Enumerable::ToArray<int32>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>)
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: call !!0[] [System.Core]System.Linq.Enumerable::ToArray<int32>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>)
IL_0014: stloc.2
IL_0015: ret

Using F1 on it will lead you to the MSDN documentation :
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.toarray?view=netframework-4.7.2

Stating that it's within the namespace: System.Linq.

IList only provide the method:

Add(Object),
Clear(),
Contains(Object),
CopyTo(Array, Int32),
GetEnumerator() Inherited from ICollection,
IndexOf(Object) Inherited from IEnumerable,
Insert(Int32, Object),
Remove(Object),
RemoveAt(Int32).


SharpLab demo to see the intermediate steps and results of code compilation.
xdtTransform
  • 1,986
  • 14
  • 34
0

As stated in the comments the ToArray() is an extension method useable on an IList in the System.Linq namespace.

The reason IList doesn't have this fuction but List does. Is because the List class has a ToArray() method defined, which IList has not. Which would explain the error on IList.ToArray()

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.toarray?view=netframework-4.7.2

JayRone
  • 97
  • 1
  • 6