1

Hey I am a newbie to C#(or programming you could say as I only learned html and css before) I was playing around with generics a bit and I made a small dictionary. There is no problem with searching the word and stuffs but when I search a word that does not match my word it throws up and error how do I solve this please help!

for (int i = 1; i <= 10; i++)
{
    Dictionary<string, string> fivewordDictionary = new Dictionary<string, string>();

    fivewordDictionary.Add("hello", "Saying greeting");
    fivewordDictionary.Add("bye", "Greeting when someone is leaving");
    fivewordDictionary.Add("programming", " I dont even know what it is");
    fivewordDictionary.Add("C#", "An object oriented programming language");
    Console.WriteLine();
    Console.Write("Word: ");

    string userWord = Console.ReadLine();

    Console.WriteLine();

    string s = userWord.ToLower().Trim();

    Console.WriteLine(userWord + ": " + fivewordDictionary[s]);
Shazi
  • 1,138
  • 8
  • 19

4 Answers4

5

Use TryGetValue on your dictionary.

var d = new Dictionary<string, int>();
d.Add("key", 0);
// This code does two hash lookups.
int value;
if (d.TryGetValue("key", out value))
{
    Console.WriteLine(value);
}

It more efficient, but more importantly, is more idomatic and clear.

You can avoid the ToLower() by picking a more lax stringcomparer when you create your dictionary.

Nathan Cooper
  • 5,499
  • 4
  • 32
  • 60
  • 2
    A far better solution than checking with `ContainsKey` – Panagiotis Kanavos Mar 16 '16 at 15:11
  • "Far better" solution, depends: the cost of the hash is negligible, except maybe for really, really tight loops. As a first step into the "world" of dictionaries, I find that ContainsKey is simpler to grasp. YMMV, I suppose. – A. Chiesa Mar 16 '16 at 15:49
4

You want to look at ContainsKey:

if (s != null && fivewordDictionary.ContainsKey(s))
{
    Console.WriteLine(userWord + ": " + fivewordDictionary[s]);
}
else
{
    Console.WriteLine(userWord + ": not found!");
}

Please note the s != null part: if you pass a null into ContainsKey, it will throw a NullReferenceException. Which is bad, bad, bad.

A. Chiesa
  • 5,367
  • 1
  • 21
  • 43
  • Thank you! You are awesome! – Reza Taibur Mar 16 '16 at 15:08
  • 1
    Just two notes: 1) don't use `ToLower()`, instead specify appropriate `StringComparer` in `Dictionary` constructor. It's not just shorter, it's wrong to don't do it. 2) `s` cannot be `null`, ever, no need to check. – Adriano Repetti Mar 16 '16 at 15:09
  • Thanks @AdrianoRepetti will remember! – Reza Taibur Mar 16 '16 at 15:10
  • @Adriano Repetti: in this case, yes, s cannot be null. But, given the topic of the answer, I prefer to highlight the most common pitfall every newbie has when working with dictionaries. A check for null too much, doesn't do any harm. A missing check, is really bad. I really wanted to convey THAT. – A. Chiesa Mar 16 '16 at 15:15
  • @A.Chiesa can you please explain why NullReferenceException is bad? I mean i dont see any error though! Thanks – Reza Taibur Mar 16 '16 at 15:21
  • As @AdrianoRepetti wrote: in your example s will NEVER be null. So, today, and only today, you can remove the check for null. But, from tomorrow, as soon as you will use a string which is not read from the command line and can be null, you can get an unhandled exception. If you insist programming, you'll learn to hate NullReferences wherever they are. – A. Chiesa Mar 16 '16 at 15:29
  • True. Just a small check wont do any harm and also a good practice as well! Thank you! – Reza Taibur Mar 16 '16 at 15:36
  • @RezaTaibur To learn more about NullReferenceException see the question "[What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)" – Scott Chamberlain Mar 16 '16 at 15:42
  • @RezaTaibur yes a small check does not harm but honestly it's more about _intent_. If I read `if (obj != null)` then I think it _may_ be `null`. No harm? Actually **code communicates wrong information** and it does harm. If it can't happen then leave it as is or - eventually - add an assertion but don't make it part of your program flow... – Adriano Repetti Mar 22 '16 at 07:50
  • @AdrianoRepetti can you please show how to do that String.Compare()? – Reza Taibur Apr 07 '16 at 08:00
  • @reza with a StringComparer not with String.Compare(). There is another dictionary constructor that accepts IComparer as parameter, use that one (example on msdn) – Adriano Repetti Apr 07 '16 at 08:06
  • @AdrianoRepetti Ok sure I was trying so bad to use the Compare() method. – Reza Taibur Apr 07 '16 at 08:09
1

Dictionary in C# will throw an error if you try to access a key that does not exist. You can solve this by first checking that the key exists. Example below:

if(dictionary.ContainsKey(key))
    Console.WriteLine(dictionary[key]);
else
    Console.WriteLine("No such key exists!");
henrikmerlander
  • 1,454
  • 13
  • 20
1

You can avoid the exception with something like that:

var dictValue = fivewordDictionary.ContainsKey(s ?? String.Empty) 
? fivewordDictionary[s] 
: "missing key";