views:

229

answers:

3

Could someone take the time to explain me the language underpinnings here :

int foo = myObject.SomeList.Count;
for (int i = 0 ; i < foo ; i++)
{
  myObject.SomeList.Add(bar);
}

goes into an infinite loop because foo references a value that keeps being incremented. Modifying the first line to:

int foo = (int)myObject.SomeList.Count;

makes it go away, somehow changing foo from reference to value once and for all. This is probably textbook but, why is this happening ?

Many thanks

EDIT : Ok, as Patrick mentions, the infinite loop only happens when there is no prior storage to foo, the cast being pointless, which makes sense. That's indeed what I thought initially while debugging this. Hence my surprise when the cast fixed it. What actually happened is that I was misled by Visual Studio into thinking I had fixed it when there was actually a problem of synchronization between edited code and executed code, which led to wrong conclusions.

+6  A: 

Are you sure?!!

int is a value type. This is not supposed to happen.

Jon Skeet, come and help!

Mehrdad Afshari
+4  A: 

The behavior you are describing can't happen in C#. You've explicitly declared the value of foo to be an int in both cases. This is a value type. By definition the instance foo points to is separate from the original instance in myObject.SomeList.Count.

Can you post a more thorough code example?

JaredPar
+8  A: 

I tried this on my system and can't replicate your problem. I could however replicate it with the following code, maybe this is what you meant:

// SomeList is not empty before the loop
for (int i = 0; i < myObject.SomeList.Count; i++)
{
    myObject.SomeList.Add(bar);
}

In this case we are not storing the Count in an int, so every time we add to the list, we are comparing i+1 with Count+1, hence the endless loop.

Patrick McDonald
Probably this is what he means, but the OP explicitly mentioned (int)myObject.SomeList.Count makes a difference which is impossible.
Mehrdad Afshari