Today I encoded a function that uses two nested foreach loops. Seeing that it is not working as expected, I debugged it. But I do not see the error and I do not think that a simple error can lead to the behavior that I noticed.
The part is as follows:
foreach(MyClass cItem in checkedListBoxItemList.Items)
{
foreach(MyClass cActiveItem in ActiveItemList)
{
if (cActiveItem.ID == cItem.ID) ;
}
}
Let's say checkedListBoxItemList.items contains 4 elements of type MyClass, and ActiveItemList is a List <MyClass> with two elements.
The debugger goes into the external foreach, reaches the internal foreach, executes if if 2 times (once per cActiveItem) and reaches the end of the external foreach.Now, the debugger returns to the head of the external foreach, as it should, But instead of starting the second round of the external foreach, the debugger suddenly jumps to the MyClass.ToString () method. I can go through this method 4 times (the number of elements in checkedListBoxItemList.Items) and then ... nothing. Visual Studio shows me my window shape, and foreach does not continue.
When changing the code to
int ListCount = checkedListBoxItemList.Items.Count;
for(int i=0; i<ListCount; i++)
{
MyClass cItem = checkedListBoxItemList.Items[i] as MyClass;
foreach(MyClass cActiveItem in ActiveItemList)
{
if (cActiveItem.ID == cItem.ID) ;
}
}
everything works fine and as intended. I showed the problem to a colleague, but he also did not understand what had happened. I don’t understand why the debugger goes into the MyClass.ToString () method. I used F10 to jump, so no need to leave a function. And even if there is a reason why the foreach loop does not continue?
Im, Visual Studio 2010, .
, , . .