Unhandled exception in foreach (object obj in list)

E

Emily

Hi,

I have the following code and an unhandled exception.

Code:

UnitInventory inventory;
foreach (object obj in list) //debugger points to list where
exception occurs
{
inventory = (UnitInventory)obj;
Console.WriteLine(inventory);
}

Error message:

"An unhandled exception of type 'System.InvalidOperationException'
occurred in mscorlib.dll

Additional information: Specified IComparer threw an exception."

Any suggestion on how to get rid of the error? Thanks!
 
J

Jon Skeet [C# MVP]

Emily said:
Hi,

I have the following code and an unhandled exception.

Code:

UnitInventory inventory;
foreach (object obj in list) //debugger points to list where
exception occurs
{
inventory = (UnitInventory)obj;
Console.WriteLine(inventory);
}

Error message:

"An unhandled exception of type 'System.InvalidOperationException'
occurred in mscorlib.dll

Additional information: Specified IComparer threw an exception."

Any suggestion on how to get rid of the error? Thanks!

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
H

Helge Jensen

Emily said:
Hi,

I have the following code and an unhandled exception.

Code:

UnitInventory inventory;
foreach (object obj in list) //debugger points to list where
exception occurs
"An unhandled exception of type 'System.InvalidOperationException'
occurred in mscorlib.dll

Additional information: Specified IComparer threw an exception."

Any suggestion on how to get rid of the error? Thanks!

The lists GetEnumerator(), or the returned IEnumerator's MoveNext() or
Current, is throwing InvalidOperationException.

To make debugging easier, rewrite the loop as:

IEnumerator it = list.GetEnumerator();
while ( it.MoveNext(); ) {
object obj = it.Current;
// stuff
}

which will allow you to step through what's happening in the foreach.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top