Unhandled exception in foreach (object obj in list)

  • Thread starter Thread starter Emily
  • Start date Start date
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!
 
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.
 
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.
 
Back
Top