Reputation: 4603
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
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