C# generic wildcards

257 views Asked by At

I spent quite some time solving this but I cannot figure it out. I have the following Java method signature:

public static <T> boolean isSameCollectionSets(
    Collection<? extends Collection<T>> set1, 
    Collection<? extends Collection<T>> set2)

This method takes two collections of collections of type T. And it works in Java. Also, the compiler is able to get the type T himself when passing correct arguments.

Now I want to port this exact same method to C#. So far, I have this:

public static bool IsSameCollectionSets<T>(ICollection<T> set1, ICollection<T> set2) 
    where T : ICollection<T>

However, this fails when I try to do the following in C#:

ICollection<List<int>> collection1 = new List<List<int>>();
ICollection<HashSet<int>> collection2 = new HashSet<HashSet<int>>();

var result = IsSameCollectionSets(collection1, collection2);

The IsSameCollectionSets method is curly underlined and the compiler says:

"The type arguments for method 'bool IsSameCollectionSets(ICollection, ICollection)' cannot be inferred from the usage. Try specifying the type arguments explicitly."

Now, I tried to give the type arguments explicitly, but nothing has worked so far.

Where is my error? Many thanks in advance!

1

There are 1 answers

0
Biocoder On BEST ANSWER

I found a working solution thanks to @Rob.

Instead of using ICollection<T> I use IEnumerable<T>:

public static bool IsSameCollectionSets<T>(IEnumerable<IEnumerable<T>> set1,
IEnumerable<IEnumerable<T>> set2)

Also, in comparison to the code in the question, I use interfaces for the instantiation:

ICollection<IList<int>> collection1 = new List<IList<int>>();
ICollection<ISet<int>> collection2 = new HashSet<ISet<int>>();