File tree Expand file tree Collapse file tree 3 files changed +41
-1
lines changed
ReadableExpressions.UnitTests Expand file tree Collapse file tree 3 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -391,6 +391,20 @@ public void ShouldOnlyRemoveParenthesesIfNecessary()
391391 Assert . AreEqual ( "(i == 1) ? string.Empty : ((int)o).ToString()" , translated ) ;
392392 }
393393
394+ [ TestMethod ]
395+ public void ShouldNotRemoveParenthesesFromACastObjectChainedMethodCall ( )
396+ {
397+ Expression < Func < IList < int > , string [ ] > > intArrayConverter =
398+ ints => ( ( int [ ] ) ints ) . ToString ( ) . Split ( ',' ) ;
399+
400+ var stringArrayVariable = Expression . Variable ( typeof ( string [ ] ) , "strings" ) ;
401+ var assignment = Expression . Assign ( stringArrayVariable , intArrayConverter . Body ) ;
402+
403+ var translated = assignment . ToReadableString ( ) ;
404+
405+ Assert . AreEqual ( "strings = ((int[])ints).ToString().Split(',')" , translated ) ;
406+ }
407+
394408 [ TestMethod ]
395409 public void ShouldUseMethodGroupsForStaticMethods ( )
396410 {
Original file line number Diff line number Diff line change @@ -22,5 +22,24 @@ public static Expression GetSubject(this MethodCallExpression methodCall)
2222 return methodCall . Method . IsExtensionMethod ( )
2323 ? methodCall . Arguments . First ( ) : methodCall . Object ;
2424 }
25+
26+ /// <summary>
27+ /// Gets the parent Expression for the given <paramref name="expression"/>.
28+ /// </summary>
29+ /// <param name="expression">The Expression for which to retrieve the parent.</param>
30+ /// <returns>The given <paramref name="expression"/>'s parent Expression.</returns>
31+ public static Expression GetParentOrNull ( this Expression expression )
32+ {
33+ switch ( expression . NodeType )
34+ {
35+ case ExpressionType . Call :
36+ return ( ( MethodCallExpression ) expression ) . GetSubject ( ) ;
37+
38+ case ExpressionType . MemberAccess :
39+ return ( ( MemberExpression ) expression ) . Expression ;
40+ }
41+
42+ return null ;
43+ }
2544 }
2645}
Original file line number Diff line number Diff line change @@ -109,7 +109,14 @@ private static bool KeepSurroundingParentheses(Expression expression)
109109 return true ;
110110
111111 case ExpressionType . Call :
112- return ( ( MethodCallExpression ) expression ) . Object ? . NodeType == ExpressionType . Convert ;
112+ var parentExpression = expression . GetParentOrNull ( ) ;
113+ while ( parentExpression != null )
114+ {
115+ expression = parentExpression ;
116+ parentExpression = expression . GetParentOrNull ( ) ;
117+ }
118+
119+ return ( expression . NodeType == ExpressionType . Convert ) ;
113120 }
114121
115122 return false ;
You can’t perform that action at this time.
0 commit comments