Skip to content

Commit

Permalink
fix Inline temporary variable adds unnecessary cast (#70423)
Browse files Browse the repository at this point in the history
  • Loading branch information
CyrusNajmabadi authored Nov 23, 2024
2 parents c2deeae + dc54192 commit bb7610d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -408,10 +408,14 @@ ExpressionSyntax CreateExpressionToInline()

return SyntaxFactory.ArrayCreationExpression(arrayType, arrayInitializer);
}
else if (isVar && expression is ObjectCreationExpressionSyntax or ArrayCreationExpressionSyntax or CastExpressionSyntax)
else if (isVar && expression is
ObjectCreationExpressionSyntax or
ArrayCreationExpressionSyntax or
CastExpressionSyntax or
InvocationExpressionSyntax)
{
// if we have `var x = new Y();` there's no need to do any casting as the type is indicated
// directly in the existing code. The same holds for `new Y[]` or `(Y)...`
// directly in the existing code. The same holds for `new Y[]` or `(Y)...` or `Y(...)`
return expression;
}
else
Expand Down
27 changes: 27 additions & 0 deletions src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5884,4 +5884,31 @@ public string M()

await TestInRegularAndScriptAsync(code, expected);
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69869")]
public async Task InlineTemporaryNoNeededVariable()
{
await TestInRegularAndScriptAsync(
"""
using System;
class A
{
void M(string[] args)
{
var [||]a = Math.Round(1.1D);
var b = a;
}
}
""",
"""
using System;
class A
{
void M(string[] args)
{
var b = Math.Round(1.1D);
}
}
""");
}
}

0 comments on commit bb7610d

Please sign in to comment.