XDracam / unity-corelibrary

Collection of classes and extension methods that make life with Unity3D more comfortable
MIT License
15 stars 3 forks source link

Utility method for constructing Enumerables with varargs #29

Closed Eregerog closed 5 years ago

Eregerog commented 5 years ago

Suggested names: All, Seq, Sequence, ...

When writing a method which takes a sequence, like void Foo(IEnumerable<int> bar), you sometimes want to call the method with a constant number of arguments like Foo(1, 2, 3). This requires you to write an additional void Foo(param int[] bar) => Foo((IEnumerable<int>) bar);.

This gets even worse if both versions are defined in an interface (which allows no default implementations), so each implementing class has the duplicate line of code void Foo(param int[] bar) => Foo((IEnumerable<int>) bar);.

An alternative to the varargs version is the array literal: Foo(new [] { 1, 2, 3 });. I really do not like this one, since the weird new [] can confuse quick readers and interrupt the flow and throught process of the person trying to understand your code.

So we propose a simple method IEnumerable<T> All<T>(param T[] elements) => elements;. So the above call would look like: Foo(All(1, 2, 3)); or Foo(Seq(1, 2, 3)); depending on how we will call it. This fits perfectly into the goal of the CoreLibrary: To provide generic utilities which you do not have to reinvent yourself.