@@ -8235,6 +8235,17 @@ internal static bool IsBlockLikeOrConditional(this ExpressionType nodeType) =>
82358235 nodeType == ExpressionType.Conditional | nodeType == ExpressionType.Coalesce ||
82368236 IsBracedBlockLike(nodeType);
82378237
8238+ // Returns true when a non-void expression used as a statement needs a `_ = ` discard prefix
8239+ // to suppress CS0201 / produce valid, unambiguous C# output.
8240+ [MethodImpl((MethodImplOptions)256)]
8241+ internal static bool NeedsDiscardWhenUsedAsStatement(this Expression expr)
8242+ {
8243+ var nodeType = expr.NodeType;
8244+ return expr.Type != typeof(void)
8245+ && (nodeType == ExpressionType.Call | nodeType == ExpressionType.Invoke
8246+ | nodeType == ExpressionType.Conditional | nodeType == ExpressionType.Coalesce);
8247+ }
8248+
82388249 [MethodImpl((MethodImplOptions)256)]
82398250 internal static bool IsReturnable(this Expression expr)
82408251 {
@@ -10927,10 +10938,7 @@ private static StringBuilder ToCSharpBlock(this Expression expr, StringBuilder s
1092710938 else
1092810939 {
1092910940 sb.NewLineIndent(lineIndent + indentSpaces);
10930- var nodeType = expr?.NodeType ?? ExpressionType.Default;
10931- var needsDiscard = expr != null && expr.Type != typeof(void)
10932- && (nodeType == ExpressionType.Call | nodeType == ExpressionType.Invoke
10933- | nodeType == ExpressionType.Conditional | nodeType == ExpressionType.Coalesce);
10941+ var needsDiscard = expr != null && expr.NeedsDiscardWhenUsedAsStatement();
1093410942 if (needsDiscard) // it requires some assignment target to avoid error or warning
1093510943 sb.Append("_ = ");
1093610944 sb = expr?.ToCSharpString(sb, EnclosedIn.ParensByDefault, ref ctx,
@@ -11155,9 +11163,7 @@ private static StringBuilder BlockToCSharpString(this BlockExpression b, StringB
1115511163 {
1115611164 sb.NewLineIndent(lineIndent);
1115711165 var nodeType = expr.NodeType;
11158- var returningCondOrCoalesceOrCall = expr.Type != typeof(void)
11159- && (nodeType == ExpressionType.Conditional | nodeType == ExpressionType.Coalesce
11160- | nodeType == ExpressionType.Call | nodeType == ExpressionType.Invoke);
11166+ var returningCondOrCoalesceOrCall = expr.NeedsDiscardWhenUsedAsStatement();
1116111167 if (returningCondOrCoalesceOrCall) // it requires some assignment target to avoid error or warning
1116211168 sb.Append("_ = ");
1116311169
0 commit comments