Reputation: 367
I have a generic method that takes Enumerables of type T. In the event that T is also an Enumerable, I need to pass it to another function. However, since that function only takes Enumerables, and T is generic, it won't compile. I'm checking that T is Enumerable before I pass it - but clearly not in a way that solves this problem.
How can I do this?
(Obviously I could write another method that only takes IEnumerable< IEnumerable< T>>, and use that where relevant, but that seems inelegant.)
Example:
public static bool EnumerablesAreEqual<T>(IEnumerable<T> a, IEnumerable<T> b)
{
foreach (T x in a)
{
if (x is Enumerable && !EnumerableContainsEnumerable(x, b))
return false;
if (!b.Contains(x))
return false;
}
...
}
I've looked at this post but I don't think it's quite the same issue.
Upvotes: 1
Views: 131
Reputation: 98496
The fact that you check the dynamic type of the variable doesn't change its static type, and that what it's used to check the call.
If you want to do that, you need a cast. You can use a checked cast to do it in one go:
Enumerable ex = x as Enumerable;
if (ex != null && !EnumerableContainsEnumerable(ex, b))
return false;
The as
operator checks whether the cast is possible: if it is it will return the casted object; if it is not, it will return null
.
Upvotes: 5