C
C#2y ago
Gladiator

Best way to Convert a single element to IEnumerable element

What is the best way (performance, memory, GC) to Convert a single element to IEnumerable<Element> elements? T => IEnumerable<T>
return new []{element};
yield return element;
return new []{element};
yield return element;
4 Replies
Anton
Anton2y ago
I would guess the best best way would be to make a custom class which holds a single (or N) elements, but I've seen people just do new[]{it} all the time so you'd need a class that implements IEnumerable, and an implementation of IEnumerator that would work on that class it's not that much code, just a bit of boilerplate idk what yield return it gives you honestly, you should look at the lowered code, it might just be doing the class thing I described
mtreit
mtreit2y ago
@Gladiator , @AntonC I was curious about this so I benchmarked it. Wrapper class certainly seems like the way to go.
Anton
Anton2y ago
i was suggesting 2 classes, an enumerable and an enumerator I would guess if you do two classes you get the same results as with the yield version