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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With