Reputation: 2443
I'm using .Net 2.0, and I've run into a strange error:
I have a hashtable using string as keys and a class (named Market) as the value. The class contains 4 integers and 1 byte. One of the integers represents a counter which I need to increment.
I have only one element in the hashtable. It's key is "Tomo"
.
I do this:
string strM = "Tomo"
MarketPlace mkt = (MarketPlace)mHash[strM];
mkt.nCter++;
In the last line I get an null reference exception, even though using the debugger I can see that the hashtable contains that instance. This code was working fine a week ago.
Upvotes: 0
Views: 2399
Reputation: 5637
Maybe you added your instance backward.
mHash.Add(instance, "Tomo")
instead of
mHash.Add("Tomo", instance)
So when you are in debugger, it may appear as if it's listed, but the key is actually the instance and "Tomo" is the object value.
Upvotes: -1
Reputation: 27419
Are you sure you're not just looking at the key in the Hashtable, where the value is null?
For example, this works:
mHash["Tomo"] = null;
Market value = (Market)mHash["Tomo"];
value.nCounter++; // NullReferenceException
Upvotes: 0
Reputation: 564413
Since you're using .NET 2.0, I recommend using a Dictionary<string, Market>
instead of a HashTable. It will provide type safety, and probably help you realize why you are having the issue in this case.
Upvotes: 1
Reputation: 99869
Locate the place where you do one of the following:
mHash[strM] = mkt;
mHash.Add(strM, mkt);
At that location, mkt
is null
.
Edit: This is based on the fact that you stated that you verified the Hashtable
contains the key. If in fact the Hashtable
did not contain the key, the following applies:
If the specified key is not found, attempting to get it returns
null
.
Upvotes: 2