dotnet / dotnet/roslyn

CS0177 and CS0161 generated despite switch being exhaustive over union

Open
#85,265 5 comments 0 reactions 1 assignee Claimed by @AlekseyTs View on GitHub
Area-Compilers Feature - Unions
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**SDK 11.0.0-rc.1.26425.128**,
`true`,
`preview `,
C#:

**Steps to Reproduce**:
(You will have to simplify/adapt the code, since it contains types you don't have.)
1. Create union:
```
public readonly union Result(Success, Failure);

public readonly record struct Success(ControlInfo Data);
public readonly record struct Failure(string Message);
```
2. Create method:
```
private bool TryGenerate(GeneratorBase generator, out TResult? result)
{
var parser = new Parser(File.ReadAllLines(testFile, Encoding.Latin1));
switch (parser.Parse()) {
case Success success:
result = generator.Generate(success.Data);
return true;
case Failure failure:
messageTextBox.Text = failure.Message;
result = default;
return false;
}
}
```
**Expected Behavior**:
Compiles just fine, because switch is exhaustive and `result` is definitely assigned and all paths return a value.

**Actual Behavior**:
Getting:
>CS0177 The out parameter 'result' must be assigned to before control leaves the current method

>CS0161 'MainForm.TryGenerate(GeneratorBase, out TResult?)': not all code paths return a value

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.