0

I have written an extension method to help with collecting crash data during error reporting. This method is designed to ensure that a key is always unique. If you have a few try/catch blocks, sometimes data can get duplicated. I'm going for reasonably easy here, not super-best practices.

The problem: changing the key if it isn't unique. When I try the below, method, I get "cannot convert from 'string' to 'TKey'". Any ideas?

    public static void AddUnique<TKey, TValue>(this System.Collections.IDictionary dictionary, TKey key, TValue value)
    {
        if(dictionary[key] != null)
        {
            var newKey = key.ToString() + "-";
            AddUnique<TKey, TValue>(dictionary, newKey, value);
        }               

        ...
    }
Mark Williams
  • 583
  • 7
  • 18

2 Answers2

2

If you know your keys will always be strings, then remove the TKey generic parameter from the method signature, and just use string in its place. Alternatively, you may want to keep both generic parameters, but change the recursive call to AddUnique<string, TValue>().

dlev
  • 48,024
  • 5
  • 125
  • 132
  • Excellent idea. It seems so obvious. So could I have a method like AddUniqueInner(System.Collections.IDictionary dictionary, string key, object value)? That would save the TValue, right? – Mark Williams Jun 25 '12 at 17:56
  • 1
    Since strings are probably the best idea for keys, I would just make the signature `AddUnique(this IDictionary dict, string key, TValue value)` – dlev Jun 25 '12 at 18:00
  • That kills the extension method though, doesn't it? That doesn't match the signature of Exception.Data.Add. – Mark Williams Jun 25 '12 at 18:09
  • No, it's still fine. The compiler knows that `TValue` will always be convertible to `object`, so the add should still work. Given that you're working with the non-generic `IDictionary`, though, your suggested signature might make more sense anyway (since you can't avoid boxing value types.) – dlev Jun 25 '12 at 18:14
  • It sure did work. Thank you for taking the time to help me - I was running into trouble until I noticed you took one of the anonymous types away for AddUnique(TValue). – Mark Williams Jun 25 '12 at 18:19
0

You cannot concatenate a string to every possible key out there. You have to solution to this problem:

  • use only strings as keys
  • use something that is unique always e.g. URL or GUID*

It's not really unique, but the probability of a collision is near 0, especially on a single machine. More info on the subject.

Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108