-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
Discussed in #6925
Originally posted by Rekkonnect January 28, 2023
Summary
Despite being provided a constant expression, using an is pattern is not considered constant. This can be safely adjusted. As an added bonus, a warning is generated by code flow analysis saying that the expression always evaluates to true or false.
Motivation
Conditional compilation symbols, reliance on runtime constants deriving from conditional statements
Description
You cannot assign an is expression on constant LHS value to a constant field. For example,
public const int A = 4;
public const bool B = A is 4; // illegal, despite the result being available for constant evaluation
public const bool C = A is not 3 and < 1 or 5; // illegal tooIn the example above, A is 4 is A == 4, but is not treated as such. A == 4 passes, A is 4 does not. My personal preference is using is wherever available, especially on enum constants, which also allows for extensibility of the pattern.
Since patterns on the RHS of the pattern matching expression are always constant (as of now), the only limitation is the LHS also being a constant expression.
Example
Consider the following repro for determining where to publish a NuGet package.