C# 7 pattern matching semantics

1.3k views Asked by At

I have the two blocks of code that I would like to think are equal:

First the if based block IF based code

Then the exact same but converted to switch case over types. (sorry for bad Resharper red squiggly markers, Resharper doesnt understand this yet)

SWITCH based code

The switch based code will throw a Null reference exception on the first return Actor.Done which is not null.

Is this a pattern match bug or is there some semantics that I am missing here?

[edit] I've found a fix for it..

Changing this:

case MessageEnvelope env:

to

case MessageEnvelope _:
    var env = m as MessageEnvelope;

Makes it all work. So that leaves me with the question, arn't those lines supposed to be exctly the same?

1

There are 1 answers

0
Neal Gafter On BEST ANSWER

This is a known bug when you capture (in a lambda) a pattern variable that was declared in a switch statement. See https://github.com/dotnet/roslyn/issues/16066