Ansered by @Hoshani in the Answer.
I have designed a string key Dictionary structure to a collection, which can be a List or a HashSet. Both are string collections, even the dictionary key is a string.
I have tried to create a generic method to add to a certain key in the dictionary, a certain item to the collection. But it has not even been possible to compile.
The problem does not seem to be in the generic definition of the collection, but in the declaration of the dictionary and collection. I can't continue, and I can't detect what I'm doing wrong. I need help. This is the code:
using System;
using System.Collections.Generic;
// NO COMPILE ERROR CS1503
void AddToCollection<T,U>(U item, U key, Dictionary<U, ICollection<U>> dict)
where T : ICollection<U>, new()
{
if (key is not null) dict[item] = new T(){item};
else dict[key].Add(item);
}
var diccHS = new Dictionary<string, HashSet<string>>();
var diccLIST = new Dictionary<string, List<string>>();
// This two sentences DOES NOT COMPILE
AddToCollection<HashSet<string>, string>("item1", "item", diccHS);
AddToCollection<List<string>, string>("item1", "item", diccLIST);
// COMPILE OK - HERE THE CAST COMPILE
void test<T,U>( ICollection<U> col) where T : ICollection<U>, new() { var hs2 = new T(); }
var hset1 = new HashSet<string>{"hh"};
var list1 = new List<string>{"hh"};
test<HashSet<string>, string>(hset1);
test<List<string>, string>(list1);
Thank you
Basically what you are saying by
Dictionary<U, ICollection<U>>is that the value part of the dictionary can be any type ofICollectionfor each key value pair.However in the code
var diccHS = new Dictionary<string, HashSet<string>>()you are limiting that type toHashSetonlyfor example, the code below won't generate the issue you have
Having that said, I think in your question you wanted all values to have the same type, for that you should fix the second part of the dictionary like this :