I am trying to store and get some values from Hashtable. when i getting the value by passing key to that hashtable it return an null. But that has table having that passed value as key.
I am adding the Hashtable key and value using some string variables.
EDIT:
Here is my code.
Hashtable hashtbl = new Hashtable();
string[,] ValueArray =new string[3,2];
ValueArray[0,0]="key1";
ValueArray[0,1]="value1";
ValueArray[1,0]="key2";
ValueArray[1,1]="value2";
ValueArray[2,0]="key3";
ValueArray[2,1]="value3";
for(int i=0;i<ValueArray.GetUpperBound(0);i++)
{
string mykey=ValueArray[i,0];
string myval=ValueArray[i,1];
if (hashtbl.ContainsKey(mykey)==false)
{
hashtbl.Add(mykey,myval);
}
}
After that i am trying to get those values like
string newVal =hashtbl[mykey].ToString();
its throws an null exception.
There are few possibilities:
nullunder themykeybefore and now you are getting it back sinceifstatement returnstruemyvalis null and your code works flawlesslymykeyis of type which has a very strange implementation ofGetHashCodeThe first 2 options are not actually possible, as
hashtbl[mykey].ToString()would throwNullObjectReference. I would also assume that this is not the real code as I can’t think of a scenario wherex.ToString()would return null, unless you forgot to mention thatmyvalis of your custom type which overrides it in a strange way.Therefore, I would assume the latter:
myvalis your type which overridesToStringin a way that it returnsnull.EDIT:
after showing your code and clarifying that the last line doesn’t return null but instead throws, it looks like the second scenario is happening. If you run your code through debugger, you will see that you are inserting null values for each entry where key index is > 2. Therefore, hashtable returns null.
This snippet is suspicious:
ValueArray.GetUpperBound(0) - 1. Try removing ‘-1’.