Home > database >  Fix Unboxing Warning with a Hashtable Object Possibly being NULL
Fix Unboxing Warning with a Hashtable Object Possibly being NULL

Time:07-27

I am working on some projects to better acclimate myself to C#. I have this code example below:

Hashtable hashtable = new Hashtable();

for(int i = 0; i < s.Length; i  )
{
    if(hashtable.ContainsKey(s[i]))
    {
        hashtable[s[i]] = (int)hashtable[s[i]]   1;
    }
    else
    {
        hashtable.Add(s[i], 1);
    }
}

for(int i = 0; i < s.Length; i  )
{
    if((int)hashtable[s[i]] == 1)
        return s[i];
}

return '\0';

I need to access the element at a specified key and update it by adding 1 to it. When I try to convert the object stored in the hashtable to an integer, it gives me this warning:

warning CS8605: Unboxing a possibly null value.
warning CS8605: Unboxing a possibly null value. 
    2 Warning(s)
    0 Error(s)

Is there a way to avoid this warning? I do not think it would be possible for a NULL to appear in my hashtable, but it is warning me just in case. Is there a way to access this value in the hashtable without unboxing it?

CodePudding user response:

The issue is that the compiler doesn't know all the details about the execution that you know. It doesn't read all the context and figure out what may or may not happen. Its focus is very narrow.

When you get to this line of code:

hashtable[s[i]] = (int)hashtable[s[i]]   1;

...you know that the key exists in the Hashtable, and that the value is an int.

The compiler doesn't know that. All it knows is that you're retrieving a value - which might be null - and casting it as an int.

It's giving you a warning instead of an error because it's possible that Object will be an int. But it's suspicious, so it's warning you that what you're doing might result in a run-time error.

("Unboxing" means that you're extracting a value type from a reference type. Here's some info on that. We don't hear that term as much because we use generics and don't use Object as much.)

You could ignore the warning, but the easier answer is just not to use Hashtable. It's not used much because there are better collection types.

I don't know what the type of s is, but let's suppose it contains strings. You could use Dictionary<string, int>. Now if the dictionary contains the key (which you've already checked) then there's no chance that the key can be null. You've specified that the values are all int, and an int can't be null. Now the compiler won't warn you because there's no risk that you're trying to convert a null Object to an int.

  • Related