This is more or less a theoretical question, based on some hands-on experience:
In my application, I have quite some threads and my colleagues have the habit of disposing of those threads, one by one, and putting the value null
in them.
I though this was a bad idea, so I created a List
of those threads, and tried to do the whole thing in a loop, something like:
private List<SomeThread> _SomeThreads = new List<SomeThread>();
...
foreach (SomeThread l_SomeThread in _SomeThreads)
{
if (l_SomeThread != null)
{
l_SomeThread.Dispose();
l_SomeThread = null;
}
}
That went sour, because of the compiler error "cannot assign to 'l_SomeThread' because it is a 'foreach iteration variable'
".
"No problem", I thought, I can just use a counter for looping through the List
.
For verification, I have created this simple piece of source code, and indeed, I had the same compiler error:
List<int> test = new List<int>();
test.Add(1); test.Add(3); test.Add(5);
foreach (int i in test)
{
i = 2*i;
}
Until here, everything is clear, as I can replace the last source by:
for (int i=0; i<test.Count(), i++)
{
i = 2 * i;
}
But now I wonder: what about non-indexable collections, which you can only run through, using a foreach
loop? Does this automatically mean that their elements cannot be altered?
Or do such collections not exist in C#, exactly for that reason? (I had a look at the C# Collections explanation and I didn't find any of them which look not "indexable")