4 ms·
Does the pattern matching also statically check that you don't try to use a failed match. What if instead of if (o is null) return; // constant patte
by adrianratnapala 10y ago
Does the pattern matching also statically check that you don't try to use a failed match.
What if instead of
if (o is null) return; // constant pattern "null"
if (!(o is int i)) return; // type pattern "int i"
WriteLine(new string('*', i));
somone forgot to return, as in
if (!(o is int i)) {
// do something
}
// incorrectly try to use `o` as an int
WriteLine(new string('*', i));
Rust uses the special `match` syntax to avoid this. But I suppose C# 7.0 also analyse the structure of the `if`s and `return`s to acheive the same effect more flexibily.
And if it can do that, could that they also start phasing in statically-checked null avoidance?
- qu4z-2 10y agoMy guess is this would be covered by the "have you initialised the variable" check, similarly to: int i; if (x == 3) { i = 2; } WriteLine(i); I'd be interested to hear the answer, though.
- Eyas 10y agoThis was a concern of mine as well, as you can see in the discussion of scope changes for pattern variables [1], the C# checks for definite assignments handle this. So: if (o is int i) { f(i); } use_int(i); // <-- error: variable `i` is not definitely assigned But then if you have: if (o is int i || (o is string s and int.TryParse(out i)) use_int(i); We know that `i` is definitely assigned at that location. [1]: https://github.com/dotnet/roslyn/issues/12597 https://github.com/dotnet/roslyn/issues/12597