Skip to content

Commit ba188c8

Browse files
VB -> C#: Parenthesize if nested - fixes #178
I haven't checked the operator precedence, let's err on the side of caution - can always refine later but it's tricky since we don't know the parent won't change precendence from VB too at this point
1 parent 4e6ae52 commit ba188c8

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -945,11 +945,16 @@ private ExpressionSyntax GetConvertMethodForKeywordOrNull(SyntaxNode type)
945945

946946
public override CSharpSyntaxNode VisitTryCastExpression(VBSyntax.TryCastExpressionSyntax node)
947947
{
948-
return SyntaxFactory.BinaryExpression(
948+
return ParenthesizeIfNested(node, SyntaxFactory.BinaryExpression(
949949
SyntaxKind.AsExpression,
950950
(ExpressionSyntax)node.Expression.Accept(TriviaConvertingVisitor),
951951
(TypeSyntax)node.Type.Accept(TriviaConvertingVisitor)
952-
);
952+
));
953+
}
954+
955+
private static CSharpSyntaxNode ParenthesizeIfNested(VBSyntax.TryCastExpressionSyntax node, BinaryExpressionSyntax castExpression)
956+
{
957+
return node.Parent is VBSyntax.ExpressionSyntax ? (CSharpSyntaxNode) SyntaxFactory.ParenthesizedExpression(castExpression) : castExpression;
953958
}
954959

955960
public override CSharpSyntaxNode VisitLiteralExpression(VBSyntax.LiteralExpressionSyntax node)

Tests/CSharp/TypeCastTests.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ public void TryCastObjectToInteger()
9090
Private Sub Test()
9191
Dim o As Object = 5
9292
Dim i As System.Nullable(Of Integer) = TryCast(o, Integer)
93+
Dim s As String = TryCast(o, Integer).ToString()
9394
End Sub
9495
End Class",
9596
@"class Class1
@@ -98,6 +99,7 @@ private void Test()
9899
{
99100
object o = 5;
100101
System.Nullable<int> i = o as int;
102+
string s = (o as int).ToString();
101103
}
102104
}");
103105
}

0 commit comments

Comments
 (0)