Search code examples
c#genericsidictionary

SortedDictionary - cant proceed if node is null


So, my code stop running when a node is null, but i .

        Node node = nodeMap[x];  (BREAKS HERE case x isn't in the tree yet)
        if(node == null)
        {
            node = new Node();
            node.Equals(x);
            nodeMap.Add(x, node);
        }

ERROR: An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in System.dll

Additional information: The key is not in the dictionary.


Solution

  • Use TryGetValue() method. If the node exists it'll retrieve it, if not it'll proceed to add the node to the dictionary. Whichever condition occurs it allows you to use the node object from there on.

    Node node = null;
    if(!nodeMap.TryGetValue(x, out node))
    {
        node = new Node();
        node.Equals(x);
        nodeMap.Add(x, node);
    }