0

I have the following code:

public class Graph<TNode> where TNode : IComparable<TNode>, IEquatable<TNode>
{
    private ISet<Node<TNode>> _nodes;
    private IDictionary<Node<TNode>, ISet<Tuple<Node<TNode>, long>>> _adjacencyList;

    public Graph()
    {
        _nodes = new HashSet<Node<TNode>>();
        _adjacencyList = new Dictionary<Node<TNode>, HashSet<Tuple<Node<TNode>, long>>>();
    }
}

The compiler complains at the part, where I try to instantiate the _adjacencyList Dictionary. It says that it cannot implicitly convert one type to the other. I was wondering, why is that? If I change the ISet in the Dictionary's key to a HashSet, everything works fine.

SalysBruoga
  • 875
  • 1
  • 9
  • 21
  • You can't. For the same reason that `IDictionary dict = new Dictionary()` would fail: neither `TKey` or `TValue` are covariants. – haim770 Apr 04 '17 at 17:21
  • You have to instantiate your Dictionary with the same signature as you have declared (using ISet, not HashSet). You can then add to your dictionary using a HashSet (e.g. `_adjacencyList.Add(node, new HashSet<...> { // data here }); – Stephen P. Apr 04 '17 at 17:23
  • @StephenPorter Oh of course.. Thank you! :) – SalysBruoga Apr 04 '17 at 17:24
  • It would work if the type parameter of `IDictionary` were [covariant](https://msdn.microsoft.com/en-us/library/dd469487.aspx). But it isn't, it is invariant. – John Wu Apr 04 '17 at 17:31

0 Answers0