dotnet / dotnet/roslyn

Applying pattern matching makes code not compilable

Open
#84,522 6 comments 0 reactions 0 assignees View on GitHub
Area-IDE
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

### Description

The following code suggests to 'merge into pattern'.
```cs
public void Foo(IEnumerable items)
{
if (items.ToList() is var data && data.Count == 0)
{
return;
}

Console.WriteLine(data);
}
```

When I use pattern matching like this:
```cs
public void Foo(IEnumerable items)
{
if (items.ToList() is { Count: 0 } data)
{
return;
}

Console.WriteLine(data);
}
```

but then the compiler says on `Console.WriteLine(data)` that `Local variable 'data' might not be initialized before accessing`.

Is that expected behavior?
Should using pattern matching make the code non-compilable?

### Reproduction Steps

Code sample above

### Expected behavior

Code should still compile, no?

### Actual behavior

Code doesn't compile

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

_No response_

### Other information

_No response_

Contributor guide

Open the contributing guide

Research direction

Start by compiling the two C# snippets from the issue and compare the definite-assignment diagnostic after replacing the `is var` condition with the property pattern. Read the compiler's pattern-matching and definite-assignment handling to determine whether the reported error is expected. Done means the behavior is resolved or clearly documented with a regression test for this example.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.