Here\'s a very handy extension, which works for an array
of anything:
public static T AnyOne(this T[] ra) where T:class
{
int k = ra
The answer is to use the original code!
This ought to be the only question on StackOverflow
where the question itself illustrates significantly better code than any of the provided answers. All suggested answers encourage the use of an interface, which will imply a significant performance hit. Do not use those solutions in production code!
Given that the question is tagged unity3d
it is apparent that he code will be part of a game. In a game, the last thing you want is intermittent stuttering due to garbage collection
. Typically, in Unity, you want enumerators to be extremely performant. Which brings me to the answer itself:
Unless you really have to. The List
and T[]
types have highly optimized value-typed enumerators. Once you cast your type to an interface, you will revert to the non-optimized reference-typed version. Every call to the non-optimized version of GetEnumerator()
will produce garbage, adding up to the stuttering that will later take place (trust me) when the garbage collector collects those allocated objects.
List.GetEnumerator()
here.IEnumerable.GetEnumerator()
here.For details, see my other answer.