1

I have the following extension method for Dictionary collection

public static IEnumerable<Dictionary<TKey, TValue>> Split<TKey, TValue>(
    this Dictionary<TKey, TValue> array, 
    int size)
{
    for (var i = 0; i < (float)array.Count / size; i++)
    {
        yield return array.Skip(i * size)
                          .Take(size)
                          .Select(t => new { t.Key, t.Value })
                          .ToDictionary(t => t.Key, t => t.Value);
    }
}

And I'm using it like this:

var batches = ItemsDictionary.APIitems.Split(20).ToList();

ItemsDictionary.APIitems gets initialized in another method and always not null and not empty when I call Split() extension method. It works just fine, but in 50% of executions it throws

System.ArgumentNullException at Extentions.DictionaryExtentions+<Split>d__0``2.MoveNext

Any ideas what could be the cause of ArgumentNullException?

Ivan Sukhetskyi
  • 113
  • 2
  • 13
  • Have you tried to debug it ? If `array` is `null` the LINQ query will throw an exception while executing the `.ToDictionary` method – Fabjan May 27 '18 at 14:21
  • Yes, many times, array was never null, in my case it contains about 100k of items every time I debug it. – Ivan Sukhetskyi May 27 '18 at 14:28
  • 3
    @IvanSukhetskyi You could set a [conditional breakpoint](https://stackoverflow.com/questions/6670415/how-to-set-conditional-breakpoints-in-visual-studio) that will only hit if certain condition has been fulfilled – Fabjan May 27 '18 at 14:31
  • @Fabjan tried several times, without success – Ivan Sukhetskyi May 27 '18 at 14:57
  • @IvanSukhetskyi Add the stacktrace to your question so we can see additional information – Fabjan May 27 '18 at 15:15
  • The null dereference exception is because you're dereferencing a null. Almost certainly `array` is null. What is more interesting about this code is: why are you using float arithmetic in the loop condition? That is a strange thing to do. – Eric Lippert May 27 '18 at 15:45
  • 3
    My recommendation is that you write your code like this pattern: `public static IE> S(this D a, int s) { if (a == null) throw …; else return SReal(a, s); }` and then write a **private** `SReal` that has the `yield`. That way you are guaranteed that the exception is thrown *when `S` is called* and not when `MoveNext` on the iterator is called. That will help you debug it. – Eric Lippert May 27 '18 at 15:51
  • 2
    Surprisingly, the standard page for null dereference debugging did not mention this technique. I've added a section explaining it in more detail at the bottom. – Eric Lippert May 27 '18 at 16:15
  • Thanks for recommendations @EricLippert, I'll try that out – Ivan Sukhetskyi May 27 '18 at 16:16

0 Answers0