Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable.ToArray<T>() vs. IEnumerable.Cast<T>().ToArray()

Tags:

c#

.net

linq

When trying to obtain an array of objects from an IEnumerable collection of objects (cast differently than the array I want), I know I can first cast the source collection to the proper type, and then obtain an array from that, but the method ToArray<T>() gives me the impression that it can handle both of those operations in one step. From my experience, though, I have never been able to find a case where the ToArray<T>() method works for any T except the original source's T (which, in my mind, makes ToArray<T>() silly, since it does the same thing that the non-generic ToArray() already does).

So my question is, am I missing the point of the ToArray<T>() method, and I'm trying to make it do something it was never intended for, or is there something silly I'm missing with regard to the method, and what I'm trying to do does generally follow its intent?

Here is a concrete example to illustrate my issue:

public interface IFoo { }
public class Foo : IFoo { }

static void Main(string[] args)
{
    // Suppose a list of Foos was created
    List<Foo> src = new List<Foo>();

    // I would be safe obtaining an array of IFoos from that list, but

    // This is not supported (although intellisense shows the method is there, the compiler balks):
    // IFoo[] results = src.ToArray<IFoo>();

    // Whereas this works just fine:
    IFoo[] results = src.Cast<IFoo>().ToArray();
}
like image 257
Steven Avatar asked Feb 25 '23 20:02

Steven


1 Answers

The reason ToArray<T>() is generic is so that it can operate on any IEnumerable<T>, not so that you can supply a different T:

public static T[] ToArray<T>(this IEnumerable<T> self) { ... }

You should never need to provide the T yourself. If you did, as in your example, the method would expect to receive, for example, an IEnumerable<IFoo>, which you are not supplying.

FYI, there is no "non-generic ToArray()". The compiler is inferring the T generic argument based on the type of enumerable you call ToArray() on.

like image 165
cdhowie Avatar answered Mar 05 '23 01:03

cdhowie