Any way to use foreach/for with Dictionary without generating junk?

Since Unity uses an old version of the Mono compiler, there is a bug that causes a heap allocation using foreach (see: It's official, foreach is bad (in Unity) - Make Games South Africa). I use dictionaries a bunch, and I am forced to enumerate over key or value collections of dictionaries (in C#).

Has anyone used viable alternatives to foreach or should I just stomach the allocations? Thanks.

You can use the underlying iterators without creating the unnecessary garbage - essentially, you write what you would have liked the compiler to generate for you. The basic pattern is:

var enumerator = collection.GetEnumerator();
while (enumerator.MoveNext()) {
    var element = enumerator.Current;
    // loop body goes here
}

It is more complex though if the enumerator type is disposable, as you need to dispose of it appropriately, even if exceptions occur in your loop body. There are more details here.

I think in modern parlance you can handle the exceptions more tidily than the linked page does, like this:

using (var enumerator = collection.GetEnumerator())
{
    while (enumerator.MoveNext()) {
        var element = enumerator.Current;
        // loop body goes here
    }
}

In practice though I would guess that any enumerator which requires disposal is going to create garbage anyway, and so you might as well just use the “foreach” in that case.