dotnet / dotnet/runtime

Incorrect stack trace line number when exception originates inside a `foreach` loop body over an iterator method in Release configuration

Open
#128,282 3 comments 0 reactions 1 assignee Claimed by @jakobbotsch View on GitHub
area-CodeGen-coreclr question
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

## Description

When an exception is thrown inside a `foreach` loop that iterates over an `IEnumerable` implemented with `yield return`, the stack trace points to the **`foreach` line** instead of the actual **line that caused the exception**. This only happens in **Release** builds; Debug builds report the correct line number.

## Steps to Reproduce

1. Create a new .NET 9 console application.
2. Replace `Program.cs` with the following code:

```csharp
namespace TestNamespace
{
public class Program
{
public static void Main(string[] args)
{
StackDumpTest();
}

class HeroInfo
{
public string skill;
public HeroInfo(string s) { skill = s; }
}

static IEnumerable GetAllHeroes()
{
yield return new HeroInfo("1");
yield return new HeroInfo(null!); // deliberately null string
yield return new HeroInfo("2");
}

public static void StackDumpTest()
{
foreach (var heroInfo in GetAllHeroes())
{
Console.WriteLine(heroInfo.skill.Length); // this is line 27
}
}
}
}
```

3. Build and run in **Release** mode (e.g., `dotnet run -c Release`).
4. Observe the stack trace in the console output.

## Expected Behavior

The `NullReferenceException` thrown because of `heroInfo.skill.Length` (where `skill` is `null`) should be reported at **line 27** (the line inside the loop body where `.Length` is accessed).

## Actual Behavior

The stack trace reports the exception at **line 25** (the `foreach` line), which is misleading:

```
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at TestNamespace.Program.StackDumpTest() in E:\...\Program.cs:line 25
at TestNamespace.Program.Main(String[] args) in E:\...\Program.cs:line 7
```

## Additional Information

- **.NET Version:** .NET 9.0 (Release build, `win-x64`)
- **OS:** Windows (x64)
- This problem does **not** occur in Debug builds (where line 27 is correctly reported).
- The issue seems specific to the interaction between `yield return` (iterator state machine) and PDB/sequence point information in release-optimized code.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.