Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ICollection / ICollection<T> ambiguity problem

Just want to make simple extension for syntactic sygar :

public static bool IsNotEmpty(this ICollection obj)
{
    return ((obj != null)
        && (obj.Count > 0));
}

public static bool IsNotEmpty<T>(this ICollection<T> obj)
{
    return ((obj != null)
        && (obj.Count > 0));
}

It works perfectly when I work with some collections, but when working with others I get

The call is ambiguous between the following methods or properties: 'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)' and 'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)'

Is there any canonical solution to this problem ?

No, I don't want to perform a cast before calling this method ;)

like image 391
Mose Avatar asked Feb 28 '23 05:02

Mose


1 Answers

It's because some collections implements both interfaces, You should convert collection to concrete interface like this

((ICollection)myList).IsNotEmpty();

Or

((ICollection<int>)myIntList).IsNotEmpty();

And yea, you will get NullReferanceException if obj == null so you can remove null check ;) which mean that your extension method just compares Count whith 0 which you can do without extension method ;)

like image 55
Arsen Mkrtchyan Avatar answered Mar 11 '23 00:03

Arsen Mkrtchyan