views:

319

answers:

3

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.

+4  A: 

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.

Darin Dimitrov
reportGraphs looks more like an enumerator than a dictionary though. Why should a dictionary return a `null` enumerator? Just wondering...
dtb
@dtb good point. It must be an `IEnumerable<T>`.
Darin Dimitrov
But `Dictionary<K,V>` implements `IEnumerable<KeyValuePair<K,V>>`, doesn't it? I believe this it where the `Value` property comes from.
Groo
Yes, sorry folks, it is indeed an enumerator.
DEH
+1  A: 

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
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
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
+2  A: 

As Darin said, reportGraphs is null if it throws a NullReferenceException. The best way would be to ensure that it is never null (i.e. make sure that it is initialized in your class' constructor).

Another way to do this (to avoid enumerating explicitly) would be to use a foreach statement:

foreach (KeyValuePair<Key,Value> item in reportGraphs)
{
    // do something
}

[Edit] Note that this example also presumes that reportGraphs is never null.

Groo
This will throw NullReferenceException if reportGraphs is null.
Darin Dimitrov
Correct, *the best way would be to ensure that it is never null*.
Groo