Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Collections Sets and Dictionaries Using Dictionaries

Larry Davis
Larry Davis
6,007 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
231,198 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
6,007 Points

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