C# C# Collections Sets and Dictionaries Using Dictionaries

Larry Davis
Larry Davis
4,581 Points

"Bummer" message says I need to increment the count each time the same word is entered; I believe this does that.

Please review my code.

LexicalAnalysis.cs
using System.Collections.Generic;

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

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

1 Answer

Steven Parker
Steven Parker
172,196 Points

You're really close, but you accidentally used the post-increment operator (++) in an unfortunate way here:

                WordCount[word] = value++;

The "post" means that the value is incremented after getting it's current value for the expression. So this just sets the dictionary value to what is already was. To set it to one higher, you could use a simple addition:

                WordCount[word] = value + 1;

Or, you could still use the post-increment operator if you apply it directly to the dictionary:

                WordCount[word]++;
Larry Davis
Larry Davis
4,581 Points

Thank you Steven. I did figure that out but wasn't sure why the ++ didn't work. Thank you for the alternative.