I’ve got a problem with some c# code I’m writing, I’m fairly new to c# and I’ve had a look around and can’t find a solution.
I’ve got a method that returns a Dictionary, I’ve set the return type to object and it seems ok.
public object loopThroughNotificationCountQueries()
{
var countQuery = new Dictionary<string, string>(); ...
... return countQuery;
}
The problem is in the main method where I’m trying to loop through the elements returned from the dictionary.
Notification notification = new Notification();
var countDictionary = notification.loopThroughNotificationCountQueries();
foreach(KeyValuePair<String, String> entry in countDictionary)
{
...
}
I’m getting an error saying “Error 2 foreach statement cannot operate on variables of type ‘object’ because ‘object’ does not contain a public definition for ‘GetEnumerator'”
Is it because I’m not specifying the correct return type for a dictionary? Or is there another way of iterating through the entries in the returned object?
Thanks for your help,
Stephen.
Look at your method declaration:
That means your
countDictionarydeclaration is effectively:… and you can’t use
foreachwith anobjectlike that. The simplest fix is to change the method declaration, e.g. to