Skip to content

Pattern Matching Boxed Primitives Differs From Unboxed Primitive #9035

Answered by huoyaoyuan
Cooksauce asked this question in Q&A
Discussion options

You must be logged in to vote

This is a question related to C# language, not runtime behavior. C# compiles them into different checks.

The behavior is similar to == with a cast. longVariable == (long)1 will success, but (long)(object)longVariable == (long)(object)1 will throw.
In other words, the pattern is interpreted at the available type information of LHS. Literal 1 will be interpreted as (object)(int)1 when LHS is object.

Boxed long does not pattern match the same way unboxed long matches.

This can't happen. Once a number is boxed, it's impractical to try every possible type.

Type check the value first, (e.g. count is long countLong && countLong is 1)

You can also use count is 1L to provide a literal of long …

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Cooksauce

This comment has been hidden.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
3 participants
Converted from issue

This discussion was converted from issue #9034 on January 09, 2025 19:50.