dotnet / dotnet/csharplang

`is` expression evaluating `const` expression should be considered constant

Open
#6,926 5 comments 46 reactions 1 assignee Claimed by @333fred View on GitHub
Needs Approved Specification Proposal Proposal champion
Dominant language
C#
Stars
12.7k
Forks
1.1k
Avg merge
11h 1m
Merged PRs (30d)
3

Description

### Discussed in https://github.com/dotnet/csharplang/discussions/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,
```csharp
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 too
```

In 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](https://sharplab.io/#v2:EYLgtghglgdgPgAQEwEYCwAoTCDMACBFANgKTwAUBXYAGygGMIAXKAexgEkYAzVzAb0x5hBfPXYBnJnmCtWNPBwkAVAKZS8AXjwBRGADcoAJ3ZhVMaVAl4AIqoAONVgE8zFvYZMw3TAHRqpAG5MIRFcPHEYDTtHFx8PY1NzaQSvHy1MAGIobjxlHQBlZQB9cgBBAGEAaTKAcULQkREYp1dk1KSLf3UmYIxM1Tpcmx0AIQBVWsam2wdW+INE72TfO31B1nsfPoGaCVVpppa49sW0lfITABNKehZ2HfMrnJCMJvDIjUIABjwAOUotVUTAASg5WBIoExWEZnORmAALDL9HJ5QolcrVOoNN4zYQAIgRTCY9gkIAA9OTYH4YJQAObApg9Xwwunk/GPPYHXF4wnE0kU8kQexQXy0hl+Vnk/Q4KkwK6qAAevgAVhJ2Bysk8XlgeaI8OZKGBZrE2u4zp0mNNBHqjqp1k4tskADSHEQBJiu20iS6sG53NgwL1NAC+mDDGCAA=) for determining where to publish a NuGet package.

## Design meetings

* https://github.com/dotnet/csharplang/blob/main/meetings/2023/LDM-2023-10-09.md#is-expression-evaluating-const-expression-should-be-considered-constant
* https://github.com/dotnet/csharplang/blob/main/meetings/2023/LDM-2023-11-27.md#making-patterns-constant-expressions

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.