26

How do I test a generic dictionary object to see whether it is empty? I want to run some code as follows:

while (reportGraphs.MoveNext())
{
    reportGraph = (ReportGraph)reportGraphs.Current.Value;
    report.ContainsGraphs = true;
    break;
}

The reportGraph object is of type System.Collections.Generic.Dictionary When running this code then the reportGraphs dictionary is empty and MoveNext() immediately throws a NullReferenceException. I don't want to put a try-catch around the block if there is a more performant way of handling the empty collection.

Thanks.

DEH
  • 1,647
  • 3
  • 25
  • 45
  • 2
    Are you sure `reportGraphs` itself isn't `null`? – dtb Jan 18 '10 at 20:24
  • 2
    `System.Collections.Generic.Dictionary` doesn't *have* a `MoveNext()` method. Are you sure you're not thinking of an iterator over a Dictionary? – Anon. Jan 18 '10 at 20:26
  • Very sorry, reportGraphs is actually defined as the .Enumerator, as in reportGraphs = new System.Collections.Generic.Dictionary.Enumerator(); So, any way to detect that MoveNext() will throw an exception when applied to the Enumerator. If I try checking for null I get Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.Dictionary.Enumerator' and '' – DEH Jan 18 '10 at 20:47

2 Answers2

39

If it's a generic dictionary, you can just check Dictionary.Count. Count will be 0 if it's empty.

However, in your case, reportGraphs looks like it's an IEnumerator<T> - is there a reason your enumerating your collection by hand?

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • You are correct - it is indeed an enumerator - sorry. There's no strong reason, its just the way the object model within the app has been structured - changing it would require quite a bit of work... – DEH Jan 18 '10 at 20:58
  • 1
    It's usually a much better approach to not work with IEnumerator directly - use a foreach loop instead, as it will typically prevent this exact scenario... – Reed Copsey Jan 18 '10 at 20:59
8

There's a difference between an empty dictionary and null. Calling MoveNext on an empty collection won't result in a NullReferenceException. I guess in your case you could test if reportGraphs != null.

Liam
  • 27,717
  • 28
  • 128
  • 190
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • reportGraphs looks more like an enumerator than a dictionary though. Why should a dictionary return a `null` enumerator? Just wondering... – dtb Jan 18 '10 at 20:26
  • But `Dictionary` implements `IEnumerable>`, doesn't it? I believe this it where the `Value` property comes from. – vgru Jan 18 '10 at 20:32
  • Yes, sorry folks, it is indeed an enumerator. – DEH Jan 18 '10 at 21:00