C# C# Collections Sets and Dictionaries The System.Collections.Generic Namespace

evanpavan
evanpavan
4,482 Points

For the previous code challenge I'm stuck at "Bummer: The given key was not present in the dictionary."

I'm getting the following error from the code challenge Bummer: The given key was not present in the dictionary. I'm not sure what to do here as the error seems wrong. I'm declaring the AddWord method and using the variable word passed in the parameter to find the WordCount int value. The variable word shouldn't be tested against the Dictionary to see if it's a key because it's an undefined variable in the current context, and the Dictionary is null for all I know.

Here's my code. Pretty straight forward. I've added the following to the given AddWord method.

 WordCount[word]++; 

Here's the full code:

using System.Collections.Generic;

namespace Treehouse.CodeChallenges
{
    public class LexicalAnalysis
    {
        public Dictionary<string, int> WordCount = new Dictionary<string, int>();

        public void AddWord(string word)
        {
            WordCount[word]++; 
        }
    }
}
evanpavan
evanpavan
4,482 Points

Here's the solution: What the error must have mean't by key does not exist is that the method we are creating needs to have additional code to handle the scenario when the key passed does not exist in the dictionary

Added an if and TryGetValue

        public void AddWord(string word)
        {
            int value;
            if(WordCount.TryGetValue(word, out value))
            {
                WordCount[word]++;
            }
            else
            {
                WordCount.Add(word, 1);
            }
         }