Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not call ToArray on a generic IEnumerable object? [closed]

Tags:

arrays

c#

public static T[] ToArray<T>(IEnumerable<T> e) {
  return e.ToArray();
}

I get the following compiler error:

Error 1 System.Collections.Generic.IEnumerable<T> does not contain a definition for ToArray and no extension method ToArray accepting a first argument of type System.Collections.Generic.IEnumerable<T> could be found (are you missing a using directive or an assembly reference?

But the MSDN reference lists this method. What is wrong here?

like image 825
John Threepwood Avatar asked Jul 11 '13 20:07

John Threepwood


People also ask

Which is faster ToList or ToArray?

ToArray might do an additional allocation and copy operation such that the buffer will be sized exactly to the number of elements. In order to confirm this the following benchmark is used. The results confirm that ToList is in most cases 10% - 15% faster.

Can I use LINQ with IEnumerable?

The IEnumerable<T> interface is central to LINQ. All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> .

What is IEnumerable<>?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

How to define IEnumerable C#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.


2 Answers

Assuming you're on .NET 3.5 or later, you need to add the using directive to the top of your code file:

using System.Linq;

You also need to have an assembly reference to System.Core (although this should be there by default for Visual Studio projects).

like image 151
Douglas Avatar answered Nov 02 '22 23:11

Douglas


You're missing using System.Linq; at the top of the file.

ToArray is an extension method implements on IEnumerable<T> as a part of LINQ (Language-Integrated Query), so you have to add that using to make it work.

like image 30
MarcinJuraszek Avatar answered Nov 02 '22 23:11

MarcinJuraszek