HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Passing a single item as IEnumerable<T>

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
ienumerablesingleitempassing

Problem

Is there a common way to pass a single item of type T to a method which expects an IEnumerable parameter? Language is C#, framework version 2.0.

Currently I am using a helper method (it's .Net 2.0, so I have a whole bunch of casting/projecting helper methods similar to LINQ), but this just seems silly:

public static class IEnumerableExt
{
    // usage: IEnumerableExt.FromSingleItem(someObject);
    public static IEnumerable FromSingleItem(T item)
    {
        yield return item; 
    }
}


Other way would of course be to create and populate a List or an Array and pass it instead of IEnumerable.

[Edit] As an extension method it might be named:

public static class IEnumerableExt
{
    // usage: someObject.SingleItemAsEnumerable();
    public static IEnumerable SingleItemAsEnumerable(this T item)
    {
        yield return item; 
    }
}


Am I missing something here?

[Edit2] We found someObject.Yield() (as @Peter suggested in the comments below) to be the best name for this extension method, mainly for brevity, so here it is along with the XML comment if anyone wants to grab it:

public static class IEnumerableExt
{
    /// 
    /// Wraps this object instance into an IEnumerable<T>
    /// consisting of a single item.
    /// 
    ///  Type of the object. 
    ///  The instance that will be wrapped. 
    ///  An IEnumerable<T> consisting of a single item. 
    public static IEnumerable Yield(this T item)
    {
        yield return item;
    }
}

Solution

Your helper method is the cleanest way to do it, IMO. If you pass in a list or an array, then an unscrupulous piece of code could cast it and change the contents, leading to odd behaviour in some situations. You could use a read-only collection, but that's likely to involve even more wrapping. I think your solution is as neat as it gets.

Context

Stack Overflow Q#1577822, score: 113

Revisions (0)

No revisions yet.