-
Notifications
You must be signed in to change notification settings - Fork 13
Description
Expression trees with a NodeType of NewArrayBounds include one or more expressions which specify the number of elements in the new array, for a given dimension. For example, the following factory-method expression tree:
NewArrayBounds(typeof(string), Constant(6))
represents the creation of an array with 6 elements, or an upper bound of 5.
However, when writing code in VB, the number in the corresponding syntax refers to the upper bound, not the number of elements. In order to get an array similar to the above, you have to write:
Dim arr = New String(5) {}
When recreating VB from the expression, if the bounds expression is a constant (in this case 6), we replace it with the constant - 1 (in this case 5).
If it's not a constant, we currently wrap it with an expression subtracting 1, such that the generated code looks like this:
Dim arr = New String(Date.Now.Day - 1) {}
However, when a VB-compiler-generated expression uses an expression as the bound, the compiler automatically wraps the expression tree node with a +1 expression:
NewArrayBounds(
typeof(DateTime),
AddChecked(
....
Constant(1)
)
)
In other words, this code:
Dim expr As Expression(Of Func(Of String())) = Function() New String(Date.Now.Day) {}
Console.WriteLine(expr.ToString("Visual Basic"))produces this string:
Function() New String(Date.Now.Day + 1 - 1) {}
We can detect this pattern and simply ignore the addition instead of wrapping with a subtraction.