ehdv
ehdv

Reputation: 4603

How to write a generic extension method which wraps object in an enumerable?

I'm trying to write an extension method which accepts an object of type T and returns IEnumerable<T>.

Here's my first attempt:

internal static class ObjectExtensions<T>
{
    public static IEnumerable<T> Yield(this T item)
    {
        yield return item;
    }
}

This function works, but only if I write ObjectExtensions<Foo>.Yield(foo): foo.Yield() doesn't resolve.

Is there a way to declare an extension method which returns a generic based on the type of the input?

(I've since discovered Enumerable.Repeat meets my original requirements, so this question is more curiosity.)

Upvotes: 0

Views: 440

Answers (1)

Alex Anderson
Alex Anderson

Reputation: 860

You do not need to specify the class as generic, only the extention method.

internal static class ObjectExtensions
{
   public static IEnumerable<T> Yield<T>(this T item)
   {
        yield return item;
   }
}

Upvotes: 6

Related Questions