I was really suprised that this question doesn't really have an answer.
For example I have a foreach loop iterating through the queue(I am using the .Net versions) what exactly happens to the queue in the foreach?
Does it simply iterates like a standard enumerator? Or does it use the Dequeue()
functionality.
For clarity:
Queue<int> q = new Queue<int>();
foreach(int i in q)
{
// what happens in this loop?
}
How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.
The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.
Does it simply iterates like a standard enumerator? Or does it use the Dequeue()
Instead of iterating the queue, it looks up elements by index and bucket in its internal array, using the Queue<T>.GetElement
method. You can see this in the implementation of the Enumerator
class returned by Queue<T>.GetEnumerator()
:
public bool MoveNext()
{
if (_version != _q._version)
ThrowHelper.ThrowInvalidOperationException(
ExceptionResource.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
_index = -2;
_currentElement = default(T);
return false;
}
_currentElement = _q.GetElement(_index);
return true;
}
Where GetElement
is simply:
internal T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With