tags:

views:

45

answers:

1

Finding myself in the situation where I have a method with this signature

void DoSomething(IEnumerable<T> before, IEnumerable<T> after)

I find myself often having to call it when I've just got one element and not IEnumerable.

I thought of adding the three overloads, but that doesn't help when one of the arguments is null.

So I thought I could just 'wrap up' my single element in an IEnumerable and send it on, but I can't find anything on Enumerable which looks like what I want (maybe I'm not looking hard enough).

So I'm looking at something like this

    public static IEnumerable<T> EnumerableUnit<T>(T item)
    {
        if(item != null) yield return item;
    }

Is this a good idea? Or is there something better I should be doing?

+5  A: 

This might help:

new[]{obj}
Mehrdad Afshari
Yup, that's definitely better (well, looks better to me) than the new List<T>(obj), which I had thought of.
Benjol
`new List<T>(obj)` requires writing down the type explicitly. Don't worry about `new`ing an array too much. If there were an `Enumerable.Unit<T>(obj)`, it would have had to instantiate a new class to return anyway.
Mehrdad Afshari
Ah. I hate inconsistent markdown interpretation in comments vs. posts.
Mehrdad Afshari