I have found the following method in an open source project:
static IEnumerable<T> Cat<T>(T t) {
yield return t;
}
As far as I understand, it does nothing else than returning an IEnumerable<T> containing t. If I am right and it’s virtual equivalent to e.g. return new List<T>{t};, what’s the purpose/advantage of using yield return here? And if I am wrong, what do I miss?
This just makes an enumerable type that contains a single element (
t). In practical terms, you are correct – it’s effectively going to be very similar to just returning a newList<T>with one element, or a new array with one element, etc.The main difference is that the returned type won’t actually be a
List<T>or an array – it’ll be a compiler generated type. You wouldn’t be able to cast the result to a list and add elements, for example. In practical purposes, it’ll behave identically to returning a newList<T>as you described.There is likely no real advantage, other than the developer probably preferred this syntax. I suspect was probably used to allow single elements to work with other portions of the API which expect an
IEnumerable<T>to be passed in, though the method name leaves a bit to be desired, IMO.