Skip to content

Commit 98c0f5b

Browse files
committed
Support for empty object initialisations + params arrays
1 parent 58074c6 commit 98c0f5b

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

ReadableExpressions.UnitTests/WhenTranslatingObjectCreations.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ public void ShouldTranslateANewExpressionWithParameters()
3030
Assert.AreEqual("new DateTime(2014, 8, 23)", translated);
3131
}
3232

33+
[TestMethod]
34+
public void ShouldTranslateAnEmptyObjectInitialisation()
35+
{
36+
var newMemoryStream = Expression.New(typeof(MemoryStream));
37+
var emptyInit = Expression.MemberInit(newMemoryStream, new List<MemberBinding>(0));
38+
39+
var translated = emptyInit.ToReadableString();
40+
41+
Assert.AreEqual("new MemoryStream()", translated);
42+
}
43+
3344
[TestMethod]
3445
public void ShouldTranslateANewExpressionWithASingleInitialisation()
3546
{

ReadableExpressions/Translators/Formatting/ParameterSet.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,12 @@ private static Func<string, string> GetParameterModifier(ParameterInfo parameter
6868
private static string FormatParamsArray(string array)
6969
{
7070
var arrayValuesStart = array.IndexOf('{') + 1;
71+
72+
if (arrayValuesStart == 0)
73+
{
74+
return string.Empty;
75+
}
76+
7177
var arrayValuesEnd = array.LastIndexOf('}');
7278

7379
var arrayValues = array
@@ -138,7 +144,7 @@ private static bool IsNotFuncType(ParameterInfo parameter, IMethodInfo method)
138144
parameterType = method.GetGenericArgumentFor(parameter.ParameterType);
139145
}
140146

141-
return
147+
return
142148
!(parameterType.FullName.StartsWith("System.Action", StringComparison.Ordinal) ||
143149
parameterType.FullName.StartsWith("System.Func", StringComparison.Ordinal)) ||
144150
// ReSharper disable once PossibleUnintendedReferenceComparison

ReadableExpressions/Translators/InitialisationExpressionTranslator.Helpers.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,16 @@ private bool ConstructorIsParameterless(TNewExpression newExpression)
5959

6060
protected static string GetInitialisation(string newExpression, string[] memberInitialisations)
6161
{
62+
if (memberInitialisations.Length == 0)
63+
{
64+
if (newExpression.EndsWith(')') || newExpression.EndsWith(']'))
65+
{
66+
return newExpression;
67+
}
68+
69+
return newExpression + "()";
70+
}
71+
6272
if ((newExpression.Length + memberInitialisations.Sum(init => init.Length + 2)) <= 40)
6373
{
6474
return $"{newExpression} {{ {string.Join(", ", memberInitialisations)} }}";

0 commit comments

Comments
 (0)