poc
poc

Reputation: 191

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary; exception getting in c#

I have a dictionary am getting thee value from the dictionary dynamically, but some times its gives exception . Can someone kindly help on this

How can i make a check the value of test[typeof(T)].Key.ColumnName, before doing some action in dictionary.

If i use !string.isnullorEmpty , there itself its throwing error. code

 int ID=123;
 private Dictionary<Type, DataTableAttribute> test
 parameters.AddInt32Parameter(test[typeof(T)].Key.ColumnName, ID);

-- thanks

Upvotes: 1

Views: 31118

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You can use ContainsKey to avoid the exception

int ID=123;
Dictionary<Type, DataTableAttribute> test

// fill test-dictionary

if (test.ContainsKey(typeof(T)) 
{
    parameters.AddInt32Parameter(test[typeof(T)].Key.ColumnName, ID);
}

Alternativly use TryGetValue:

DataTableAttribute attr;
if (test.TryGetValue(typeof(T), out attr) 
{
    // ...
}

Upvotes: 3

Related Questions