Reputation: 5884
Like I see, most IEnumerable extensions eats IEnumerable and then vomits also IEnumerable. Is it possible to make an extension method, which can eat any IEnumerable (like List) and then return the same type - List?
For example, I want to iterate over collection, if something is wrong, I will throw exception, but if all is OK, I need to return same instance (same type).
Upvotes: 2
Views: 209
Reputation: 79441
I don't see how doing this could be beneficial, but you can solve the generics part of the problem like this:
public static TEnumerable MyExtensionMethod<T, TEnumerable>(this TEnumerable enumerable)
where TEnumerable : IEnumerable<T>
{
...
}
However, you may find it difficult to actually implement such a thing because there is no generic way to create the TEnumerable
you want to return.
For example, I want to iterate over collection, if something is wrong, I will throw exception, but if all is OK, I need to return same instance (same type).
Does the following extension method not accomplish what you really want? I don't understand why you want to return the same instance.
public static void Consume<T>(this IEnumerable<T> enumerable)
{
foreach (var item in enumerable)
{
// Do nothing
}
}
Upvotes: 2
Reputation: 203821
You need to use two generic arguments:
public static TEnumerable Foo<TEnumerable, TItem>(this TEnumerable sequence)
where TEnumerable: IEnumerable<TItem>
{
return sequence;
}
Note that as a result of this change you're not going to be able to infer the generic arguments when invoking this method; you're going to have to specify them explicitly.
Upvotes: 3