Skip to content
Browse files

InsertParenthesesVisitor: insert parenthesis in "(new int[1])[0]"

  • Loading branch information...
1 parent 6955479 commit f5f1522cfcf18607f8708788c67d55b7d0f8cfd3 @dgrunwald dgrunwald committed Jul 27, 2011
View
33 NRefactory/ICSharpCode.NRefactory.Tests/CSharp/InsertParenthesesVisitorTests.cs
@@ -345,5 +345,38 @@ public void Logical4()
Assert.AreEqual("a && (b || c)", InsertRequired(expr));
Assert.AreEqual("a && (b || c)", InsertReadable(expr));
}
+
+ [Test]
+ public void ArrayCreationInIndexer()
+ {
+ Expression expr = new IndexerExpression {
+ Target = new ArrayCreateExpression {
+ Type = new PrimitiveType("int"),
+ Arguments = { new PrimitiveExpression(1) }
+ },
+ Arguments = { new PrimitiveExpression(0) }
+ };
+
+ Assert.AreEqual("(new int[1]) [0]", InsertRequired(expr));
+ Assert.AreEqual("(new int[1]) [0]", InsertReadable(expr));
+ }
+
+ [Test]
+ public void ArrayCreationWithInitializerInIndexer()
+ {
+ Expression expr = new IndexerExpression {
+ Target = new ArrayCreateExpression {
+ Type = new PrimitiveType("int"),
+ Arguments = { new PrimitiveExpression(1) },
+ Initializer = new ArrayInitializerExpression {
+ Elements = { new PrimitiveExpression(42) }
+ }
+ },
+ Arguments = { new PrimitiveExpression(0) }
+ };
+
+ Assert.AreEqual("new int[1] { 42 } [0]", InsertRequired(expr));
+ Assert.AreEqual("(new int[1] { 42 }) [0]", InsertReadable(expr));
+ }
}
}
View
5 NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/InsertParenthesesVisitor.cs
@@ -132,6 +132,11 @@ public override object VisitInvocationExpression(InvocationExpression invocation
public override object VisitIndexerExpression(IndexerExpression indexerExpression, object data)
{
ParenthesizeIfRequired(indexerExpression.Target, Primary);
+ ArrayCreateExpression ace = indexerExpression.Target as ArrayCreateExpression;
+ if (ace != null && (InsertParenthesesForReadability || ace.Initializer.IsNull)) {
+ // require parentheses for "(new int[1])[0]"
+ Parenthesize(indexerExpression.Target);
+ }
return base.VisitIndexerExpression(indexerExpression, data);
}

0 comments on commit f5f1522

Please sign in to comment.
Something went wrong with that request. Please try again.