7

I have the following code:

bool CheckStream(Stream stream) => 
    stream.CanSeek && stream.Length < 42;

I want to change it to:

bool CheckStream(Stream stream) => 
   stream is { CanSeek: true, Length < 42 };

Now I wonder, it this save? Meaning, is CanSeek evaluated before length in the property pattern? Because if not, it could throw a "NotSupportedException".

Can I expect property pattern always to be evaluated from left to right?

PS: When I tried it in C# Interactive it worked. And it throws the Exception, if I put Length: < 42 before CanSeek: true. But I wondered if this is defined this way. I didn't found anything about that. If not, I think it would be possible that the code behaves different after optimization.

2

1 Answer 1

7

The order is not specified according to the draft specification, emphasis mine:

Given a match of an expression e to the pattern type { property_pattern_list }, it is a compile-time error if the expression e is not pattern-compatible with the type T designated by type. If the type is absent, we take it to be the static type of e. [...]

At runtime, [...] each property_subpattern field or property is read and its value matched against its corresponding pattern. The result of the whole match is false only if the result of any of these is false. The order in which subpatterns are matched is not specified, and a failed match may not match all subpatterns at runtime.

So no, you should not expect that the properties are evaluated from left to right.

Sign up to request clarification or add additional context in comments.

1 Comment

That's talking about sub-patterns during positional matching as it's one of the sub-headers of that section (I think). Either way there's a broader section later on in the document called "Order of evaluation in pattern-matching" which basically says the compiler is allowed to re-order and properties should be side-effect free. This is a draft proposal and I know we're slow on formally adopting so I wonder if any guarantees have changed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.