IEnumerable.ToArray <T> () vs IEnumerable.Cast <T> (). ToArray ()
When I try to get an array of objects from a collection of IEnumerable objects (different from the array I want), I know that I can first pass the source set to the appropriate type and then get the array from this, but the ToArray<T>() method gives the impression that it can handle both of these operations in one step. However, from my experience, I could never find a case where the ToArray<T>() method works for any T except the original source T (which, in my opinion, makes ToArray<T>() stupid, since it does the same , which is no longer common ToArray () ).
So my question is: I missed the point of the ToArray<T>() method, and I'm trying to get it to do something that it never intended for, or is there something stupid. m is missing regarding the method, and what am I trying to do usually follows his intention?
Here is a concrete example illustrating my problem:
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(); } The reason ToArray<T>() is common, so it can work on any IEnumerable<T> , and not that you can specify a different T :
public static T[] ToArray<T>(this IEnumerable<T> self) { ... } You never need to provide T yourself. If you did this, as in your example, the method would expect to get, for example, an IEnumerable<IFoo> , which you do not supply.
FYI, there is no "non-generic ToArray ()". The compiler outputs a generic argument T , based on the type of the enumerated type that you call ToArray ().