#4153·ILSpy

foreach is lost when a named argument inlines the loop variable

Author: siegfriedpammerCreated Sep 19, 2026Updated Sep 19, 2026

Problem

When a call inside a foreach body uses named arguments, NamedArgumentTransform hoists an argument into a named-argument block. If the loop variable is read exactly once, and that read is a member access on it, the loop variable's assignment gets inlined into the block, and the foreach pattern can no longer be recognised. The loop is emitted as using + while (MoveNext()) instead.

Repro

csharp
using System.Collections.Generic;

public static class C
{
	private static int G(int i) => i;
	private static int M(int x, int y) => x + y;

	public static int Sum(Dictionary<int, int> d)
	{
		int s = 0;
		foreach (KeyValuePair<int, int> kv in d)
			s += M(y: G(kv.Key), x: G(2));
		return s;
	}
}

Compiled with -optimize+ against net10.0.

Actual

csharp
public static int Sum(Dictionary<int, int> d)
{
	int num = 0;
	using Dictionary<int, int>.Enumerator enumerator = d.GetEnumerator();
	while (enumerator.MoveNext())
	{
		num += M(y: G(enumerator.Current.Key), x: G(2));
	}
	return num;
}

Expected

A foreach loop, as ILSpy produces for the same body without named arguments.

Scope

Tested on master 29b348019:

shape result
Dictionary<K,V>, kv.Key in a named argument foreach lost
List<KeyValuePair<K,V>>, kv.Key in a named argument foreach lost
KeyValuePair<K,V>[] (array), same body foreach kept
Dictionary<K,V>, loop variable passed whole (H(kv)) foreach kept
Dictionary<K,V>, loop variable read twice foreach kept
List<int> / int[] / IEnumerable<int>, G(i) foreach kept

So it takes all three of: an enumerator-based foreach (arrays are not affected), the loop variable read exactly once, and that read being a member access on it, so the whole Current chain can be inlined into the named-argument block.

Note

This is not specific to indexers and does not come from #4043 - the repro above is a plain static method, and it reproduces on master without that branch. #4043 lets the same transform apply to element accesses, so it widens the set of code that can run into this, but the mechanism and the fix belong to NamedArgumentTransform / inlining.

Posted by an AI agent (Claude) on Siegfried's behalf.