1

I have created an IDictionary extension to write IDictionary Exception.Data values to a string.

The extension code:

public static class DictionaryExtension
{
    public static string ToString<TKey, TValue>(this IDictionary<TKey, TValue> source, string keyValueSeparator, string sequenceSeparator)
    {
        if (source == null)
            throw new ArgumentException("Parameter source can not be null.");

        return source.Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value + sequenceSeparator), sb => sb.ToString(0, sb.Length - 1));           
    }
}

When I use this extension on Exception.Data.ToString("=", "|") I get error

The type arguments cannot be inferred from the usage.

Any idea how to solve this?

walther
  • 13,466
  • 5
  • 41
  • 67
Tomas
  • 17,551
  • 43
  • 152
  • 257
  • The problem is probably related to the fact that `Exception.Data` is an `IDictionary`, not an `IDictionary<,>`. I'm surprised it calls the extension method at all. – Thom Smith Aug 30 '12 at 12:48
  • @ThomSmith: It doesn't call the extension method. The **compiler error** happens on the line `Exception.Data.ToString("=", "|")` – Daniel Hilgarth Aug 30 '12 at 12:50
  • Check this [Convert object htmlAttributes to string][1] [1]: http://stackoverflow.com/questions/6434865/passing-an-object-to-html-attributes – ayette May 24 '14 at 00:52

2 Answers2

7

Exception.Data is of type IDictionary, not IDictionary<TKey, TValue>.

You need to change your extension method to this:

public static string ToString(this IDictionary source, string keyValueSeparator,
                                                       string sequenceSeparator) 
{ 
    if (source == null) 
        throw new ArgumentException("Parameter source can not be null."); 

    return source.Cast<DictionaryEntry>()
                 .Aggregate(new StringBuilder(),
                            (sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value
                                                  + sequenceSeparator),
                            sb => sb.ToString(0, sb.Length - 1));            
} 
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

The exception is pointing that you are missing a cast. I copied your code in a test project but I was unable to reproduce your error. Try using x.Key.ToString() and x.Value.ToString(). The only thing I found is an error raised when Dictionary is empty: sb.ToString(0, sb.Length - 1) when lenght is zero is not working

Vlaevski
  • 1
  • 1