Reza Taibur
Reza Taibur

Reputation: 11

Error in generics C#!

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]);

Upvotes: 1

Views: 112

Answers (4)

You can avoid the exception with something like that:

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

Upvotes: 1

Nathan
Nathan

Reputation: 6531

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.

Upvotes: 5

henrikmerlander
henrikmerlander

Reputation: 1574

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!");

Upvotes: 1

Alberto Chiesa
Alberto Chiesa

Reputation: 7350

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.

Upvotes: 4

Related Questions