Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods for both ICollection and IReadOnlyCollection

Tags:

c#

icollection

I want to write an extension method (e.g. .IsEmpty()) for both ICollection and IReadonlyCollection interfaces:

public static bool IsEmpty<T>(this IReadOnlyCollection<T> collection)
{
  return collection == null || collection.Count == 0;
}

public static bool IsEmpty<T>(this ICollection<T> collection)
{
  return collection == null || collection.Count == 0;
}

But when I use it with classes implemeting both interfaces, I obviously get the ‘ambiguous invocation’. I don't want to type myList.IsEmpty<IReadOnlyCollection<myType>>(), I want it to be just myList.IsEmpty().

Is this possible?

like image 978
user1067514 Avatar asked Oct 22 '22 01:10

user1067514


1 Answers

Given that they both inherit from IEnumerable<T> you could avoid the ambiguity issue by doing an extension on that instead:

public static class IEnumerableExtensions
{
    public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
    {
        return enumerable == null || !enumerable.Any();
    }
}
like image 123
Timothy Walters Avatar answered Nov 15 '22 04:11

Timothy Walters