1

I need to increase the value of a specific key in a Hashtable, here is my code (I want to create the Hashtable during the function, and I want the table to be like that - <string><int>):

public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
        table[ipSend]++;        //error
}

By the way, can I define a Hashtable like I wrote above?

Rand Random
  • 6,633
  • 10
  • 37
  • 81
Chedva
  • 73
  • 8

2 Answers2

0
public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
    {
        int value = (int)table[ipSend];
        table[ipSend] = value + 1;
    }
}

In my opinion, a Dictionary approach would be much better because it is type safe and eliminates the casting. Hashtables are not suitable for this kind of usage. Just an example:

public void getMssg(string ipSend, string mssg, Dictionary<string,int> table)
{
    if (table.ContainsKey(ipSend))
        table[ipSend] += 1;
    else
        table.Add(ipSend, 1);
}

I updated the above code following the advice of @mjwills: TryGetValue outperforms ContainsKey:

public void getMssg(string ipSend, string mssg, IDictionary<string, int> table)
{
    int result;

    if(!table.TryGetValue(ipSend, out result))
        result = 0;

    table[ipSend] = result + 1;
}
Tommaso Belluzzo
  • 22,356
  • 7
  • 68
  • 95
0

Use a Dictionary<string, int> instead.

public void getMssg(string ipSend, IDictionary<string, int> table)
{
    int result;
    if(!table.TryGetValue(ipSend, out result))
        result = 0; // do something if the key is not found
    table[ipSend] = ++result;
}
Igor
  • 58,317
  • 10
  • 91
  • 160