Pattern Matching:is var XX and
,XX
can be used by other paths
#7561
-
Expect public Task<List<int>> GetListA() => Task.FromResult(new List<int>());
public Task<(int, int, int)> GetTupleA() => Task.FromResult((1, 2, 3));
public async Task Test() {
if (await GetListA() is var list1 && list1.Count == 0 && list1 is []) {
throw new Exception();
}
_ = list1; // can use
if (await GetListA() is var list2 and { Count: 0 } and []) {
throw new Exception();
}
_ = list2; // error: Use of unassigned local variable 'list2'
// There are other types of uses
if (await GetTupleA() is var (a1, b1, c1) and (>10, >100, >1000)) {
throw new Exception();
}
_ = (a1, b1, c1); // error
if (await GetTupleA() is var (a2, b2, c2) && a2 >10 && b2 >100 && c2 >1000) {
throw new Exception();
}
_ = (a2, b2, c2); // can use
} Language version of the above code: <TargetFramework>net7.0</TargetFramework>
<LangVersion>preview</LangVersion> |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
I don't understand what this discussion is asking. Closing out given no actual question provided. |
Beta Was this translation helpful? Give feedback.
-
I think it has to do with the way that pattern combinators behave differently from Boolean operators in conditional statements, specifically in how they impact definite assignment. But I don't know what the discussion is other than pointing it out. |
Beta Was this translation helpful? Give feedback.
-
The example code expects the variable |
Beta Was this translation helpful? Give feedback.
The variable
list2
is available, but it is not definitely assigned. If any part of the pattern fails, the entire pattern fails, thus the pattern variable never receives a value. That's what makes it different from the comparable logic using Boolean operators, and that is an intentional part of the design.