Skip to content

Commit d6f0137

Browse files
committed
Using explicit type name for variables assigned to a different type
1 parent 2401cef commit d6f0137

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

ReadableExpressions.UnitTests/WhenFormattingCode.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,22 @@ public void ShouldDeclareAVariableIfUsedBeforeInitialisation()
219219
Assert.AreEqual(EXPECTED.TrimStart(), translated);
220220
}
221221

222+
[TestMethod]
223+
public void ShouldNotVarAssignAVariableOfNonImpliedType()
224+
{
225+
var intsVariable = Expression.Variable(typeof(IEnumerable<int>), "ints");
226+
var newArray = Expression.NewArrayBounds(typeof(int), Expression.Constant(2));
227+
var assignment = Expression.Assign(intsVariable, newArray);
228+
229+
var block = Expression.Block(new[] { intsVariable }, assignment);
230+
231+
var translated = block.ToReadableString();
232+
233+
const string EXPECTED = "IEnumerable<int> ints = new int[2];";
234+
235+
Assert.AreEqual(EXPECTED, translated);
236+
}
237+
222238
[TestMethod]
223239
public void ShouldNotVarAssignAnOuterBlockDeclaredVariable()
224240
{

ReadableExpressions/Translators/BlockExpressionTranslator.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,13 @@ private static bool StatementIsTerminated(string translation, Expression express
105105

106106
private static string GetVariableTypeName(BinaryExpression assignment)
107107
{
108-
return assignment.Right.NodeType == ExpressionType.Lambda
109-
? assignment.Right.Type.GetFriendlyName()
110-
: "var";
108+
if ((assignment.Left.Type != assignment.Right.Type) ||
109+
(assignment.Right.NodeType == ExpressionType.Lambda))
110+
{
111+
return assignment.Left.Type.GetFriendlyName();
112+
}
113+
114+
return "var";
111115
}
112116

113117
private static IEnumerable<string> ProcessBlockContents(IList<string> lines, BlockExpression block)

0 commit comments

Comments
 (0)