dotnet / dotnet/csharplang

[Proposal]: Variable declarations under disjunctive patterns

Open
#8,622 0 comments 0 reactions 1 assignee Claimed by @333fred View on GitHub
Proposal champion
Dominant language
C#
Stars
12.7k
Forks
1.1k
Avg merge
11h 1m
Merged PRs (30d)
3

Description

# Variable declarations under disjunctive patterns

* Specification: https://github.com/dotnet/csharplang/blob/main/proposals/pattern-variables.md
* Discussion: https://github.com/dotnet/csharplang/discussions/8621

## Summary
[summary]: #summary

- Allow variable declarations under `or` and `not` patterns and across `case` labels in a `switch` section to share code.
```cs
if (e is C c or Wrapper { Prop: C c })
return c;

Expr Simplify(Expr e)
{
switch (e) {
case Mult(Const(1), var x):
case Mult(var x, Const(1)):
case Add(Const(0), var x):
case Add(var x, Const(0)):
return Simplify(x);
// ..
}
}
```
Instead of:

```cs
if (e is C c1)
return c1;
if (e is Wrapper { Prop: C c2 })
return c2;

Expr Simplify(Expr e)
{
switch (e) {
case Mult(Const(1), var x):
return Simplify(x);
case Mult(var x, Const(1)):
return Simplify(x);
case Add(Const(0), var x):
return Simplify(x);
case Add(var x, Const(0)):
return Simplify(x);
// ..
}
}
```

- Also relax single-declaration rules within expression boundaries as long as each variable is assigned once.
```cs
if (e is C c || e is Wrapper { Prop: C c }) ;
if (b ? e is C c : e is Wrapper { Prop: C c }) ;
```

- Also relax single-declaration rules within conditions of an `if/else`:
```cs
if (e is C c) { }
else if (e is Wrapper { Prop: C c }) { }
```

## Design meetings

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.