C Sharp - Compiler error CS1503 - cannot convert from Dictionary, ICollection, List, HashSet

735 Views Asked by At

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

1

There are 1 best solutions below

1
Hoshani On

Basically what you are saying by Dictionary<U, ICollection<U>> is that the value part of the dictionary can be any type of ICollection for each key value pair.

However in the code var diccHS = new Dictionary<string, HashSet<string>>() you are limiting that type to HashSet only

for example, the code below won't generate the issue you have

var keyValuePairs = new Dictionary<string, ICollection<string>>(){
    {"key", new HashSet<string>()},
    {"key2", new List<string>()}
};
AddToCollection<HashSet<string>, string>("item1", "item", keyValuePairs);

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 :

void AddToCollection<T, U>(U item, U key, Dictionary<U, T> dict)
     where T : ICollection<U>, new()
{
    if (key is not null) dict[item] = new T() { item };
    else dict[key].Add(item);
}