Add ability to put multiple statements into condition for if and while.
Example:
if (
var p = GetPoint();
p.X += 10;
p.Length > 20)
{
...
}
Last statement (required) is expression that provide bool value.
Benefits:
There's an issue about "statement expressions" somewhere around.
This would be the "semi-colon expressions" that were proposed on CodePlex for C# 6.0 but were finally cut. Here's a mention: C# Design Notes for Dec 16, 2013
Those expressions would have extended to anywhere in the language:
bool b = (var p = GetPoint(); p.X += 10; p.Length > 20);
However considering the variable scoping of out and pattern variables to remain consistent the declared variable p would have to remain in the enclosing scope:
if ((var p = GetPoint(); p.X += 10; p.Length > 20)) {
...
}
// p is still in scope here
Here it is, Sequence Expressions: #6182
@HaloFour
The difference is that last statement (bool expression) allow for typeswitch, while #6182 probably not
@vbcodec
Is that in reference to the scope statement?
@HaloFour
Corrected, I meant #6182
@vbcodec
I don't see why sequence expressions would preclude type switch. The last statement in the sequence can be any expression, including a bool expression. Other than the fact that this proposal limits the sequence to within if and while conditions what differentiates it?
@HaloFour A pair of parentheses. I think the same thing for tuples is to be considered inside switch, default, method invocations etc, because double parentheses look confusing IMO,
This feature is also proposed for C++17 (link).
@alrz
That could be "fixed" by changing the spec to allow the if, while and do statements to accept a Boolean sequence expression directly:
_if-statement_:
if (_boolean-expression_)_embedded-statement_
if (_boolean-expression_)_embedded-statement_else_embedded-statement_
if_boolean-sequence-expression_ _embedded-statement_
if_boolean-sequence-expression_ _embedded-statement_else_embedded-statement_
Then both of the following would work:
bool b = (var p1 = GetPoint(); p1.X += 10; p1.Length > 20);
if (var p2 = GetPoint(); p2.X += 10; p2.Length > 20) {
...
}
@HaloFour
With #6182 you cannot use typeswitch while assigning value to variable, because you can write
bool b = (var p = GetPoint(); p.X += 10; p.Length > 20 && p is Point3d p3d);
which is incorrect. And that double braces.
Whils similar grammatically and semantically, they need different implementations.
@vbcodec
I don't see why not? A type-switch is just a Boolean expression that also assigns a variable. You can use it as follows:
bool b = p is Point3d p3d;
Of course p3d wouldn't be definitely assigned after that statement, but that's no different than various other situations with type switch:
if (x == y || p is Point3d p3d) {
// oops, p3d not definitely assigned here
}