Skip to content

VB -> C#: Evaluation order and typing improvements for loops, arrays and small integers - #1331

Merged
GrahamTheCoder merged 99 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/trusting-cray-nv658p
Nov 28, 2026
Merged

GrahamTheCoder merged 99 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/trusting-cray-nv658p

Conversation

@GrahamTheCoder

@GrahamTheCoder GrahamTheCoder commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Fixes #1211

Problem

VB converts each array initializer item to the target element type, but C#'s new[] { ... } infers its type from the items alone. Take MyMethod({"foo", "bar"}) where MyMethod(keys As Key()) and Key has a widening conversion from String. That converted to a string[], which fails with CS1503.

Fixing that showed related places where the conversion compiled but behaved differently from VB, so this PR covers those areas rather than only the one report.

Solution

Array initializers (#1211, first commit 5347f29)

  • InitializerConverter uses new[] only when every item's own type already equals the element type, checking nested initializers recursively. Otherwise it writes the type, e.g. new Key[] { "foo", "bar" }.
  • This also fixes Object() targets:
    • {1, 2} gave an int[] (CS0029).
    • {1, "a"} gave CS0826.
    • {"a", "b"} gave a string[] that throws ArrayTypeMismatchException on writes.

Byte/SByte/Short/UShort operator results (new SmallIntegerOperatorPromotion)

  • VB keeps the small type as the result of arithmetic, bitwise, shift and unary operators, whereas C# promotes it to int. Using the VB semantic model, the converter casts the result back wherever the int would be visible:
    • Object and enum targets;
    • lambda returns and nullable operands;
    • If(x, y);
    • widening to another numeric type where the value would differ.
  • It does not cast where the value is already in range, or where the consumer is another operator, a comparison, a CByte/CInt, Select Case or an unformatted interpolation.
  • Shift counts are masked by the width of the shifted type, as in VB, and constant counts are folded.
  • Not works on nullable operands, and on Double/Single/Decimal operands, which VB converts to Long first.
  • unchecked is added only where a constant wraps around. Whether an enclosing operator already provides it is decided from the VB tree on the way down, so the C# is never rewritten afterwards.
  • Fractional constants are folded to VB's banker's-rounded value. Array bounds are rounded before + 1.

Compound assignments

  • When lhs op= rhs is split into lhs = lhs op rhs, the receiver, indices and operands are each evaluated once, in VB's order:
    • Array and structure storage is held as array and index locals.
    • A ref local is used only for storage that can't be split up that way, and never across Await.
    • An earlier local is captured first if something later on the line could change it: a ByRef argument, a lambda, a query, or a call made while a Static local is live.
  • Every compound operator that VB binds late (Option Strict Off with an Object operand) uses the matching Operators.*Object call. That includes /=, \=, ^=, &= and parameterized properties. A constant Nothing binds statically, as in VB.
  • ^/^= are lifted over Nullable operands and converted back to the left side's type.
  • Setter values passed to a parameterized property are named after the setter's own parameter.

Constants and defaults (new DeclaredConstantConverter)

  • Parameter defaults, DefaultParameterValue, enum member values and attribute arguments (including Object arrays) are converted to their declared type as C# constants.
  • Decimal defaults are emitted as DecimalConstant, and Object constants keep VB's type and value.
  • Omitted Optional ByRef enum and Object arguments get VB's typed default.

For loops

  • From, To and Step are each evaluated once, in VB's order.
  • The control variable is assigned only after all three are evaluated. This only matters, and only changes the output, where a Try, Catch, Finally or On Error could see the variable.
  • A Step that can't change and costs nothing to read stays inline, so simple loops keep their usual shape.

Concatenation

  • & and &= with an enum give its number.
  • A Nullable that is Nothing gives "" instead of throwing.
  • Nullable Date and enum operands use Conversions.ToString.
  • Char &= "z" compiles.

Generated names

  • Pattern variables and hoisted temporaries (loopTo, loopStep, loopFrom) stay clear of locals in sibling scopes and in the bodies of block headers: If, ElseIf, Select, Case, Catch When, With, Using and loops.
  • Names are cached per block, so this stays linear.

Other

  • CONTRIBUTING.md now says to prefer the symbol and type APIs over the slower GetOperation where either works.
  • .gitattributes marks web/package.json as -text, so its line endings stop flipping.

Post-processing of generated C# (against the advice in CONTRIBUTING.md):

  • DocumentExtensions.CsWouldBeSimplifiedIncorrectly now protects only a cast of a literal directly inside unchecked, plus a negative literal cast to a non-keyword type such as (Col)(-1).
  • Those are the shapes the Roslyn simplifier breaks. unchecked((int)0x80000010) loses its cast and becomes a uint, and (E)(-1) loses its parentheses and parses as a subtraction.
  • The old guard covered every cast inside unchecked together with all its ancestors, which left redundant parentheses around the new casts.
  • A self-verifying test covers negative hex literals in these constants.

Changed expectations: each one was checked to be semantically correct, and most were previously wrong or failed to compile. Examples:

  • new object[] { "a" }, new Action[] { … }, new List<object>(new object[] { … }).
  • (int)(short)(s * s) in a ValueTuple.
  • new float[(int)Math.Round(7d / someInt) + 1] used to round after adding one.
  • CInt(1.0) becomes 1.
  • _points(Idx()).X += o is now evaluated once, through receiver and index locals.
  • x \= 4 on a Double gives x = (long)Math.Round(x) / 4L.
  • n ^= 2 on Integer? gives n = n.HasValue ? (int)Math.Round(Math.Pow(n.Value, 2d)) : null.
  • Some For loops now declare loopTo/loopStep before the loop.
  • Issue590EnumConvertsToNumericStringAsync compiles; it was CS0019 before.

Scope: much larger than the issue. 5347f29 fixes #1211 on its own; the rest can be split out if you prefer.

Most in need of attention:

  • MethodBodyExecutableStatementVisitor, which holds the compound-assignment splitting and the For loop changes.
  • SmallIntegerOperatorPromotion.

Known gaps (pre-existing, out of scope):

  • VB integer overflow checks in general: a narrowing Step that overflows, integral /= Nothing, and a negative Step on Byte.

  • Compound assignments on late-bound indexing or invocation.

  • For with an Object control variable.

  • On Error Resume Next resuming into a loop body.

  • A few Nothing conversions:

    • DirectCast(<Object Nothing>, Integer) throws a NullReferenceException where VB gives 0.
    • A String Nothing converted to Integer? gives 0 where VB gives Nothing.
    • CObj(Nothing) as an Optional default fails to compile.
  • At least one test covering the code changed:

    • many new conversion tests, including the new SmallIntegerOperatorTests.cs and CompoundAssignmentTests.cs;
    • about 40 new self-verifying fixtures in Tests/TestData/SelfVerifyingTests/VBToCS, which compile and run both the VB and the converted C# and compare the results.

    Full suite on net10.0: 2,390 passed, 5 skipped, 0 failed. The same 5 were skipped before.

Process

  • Attachment level: low. Written with an LLM, directed and checked through blind review.
  • LLM primarily used: Claude Opus 5.5 (Claude Code), with blind-review and fix subagents.
  • Thirteen blind adversarial review rounds:
    • Each compiled and ran both the VB and the converted C# over thousands of generated cases.
    • Each compared those cases against the previous commit.
    • Every finding was fixed or is listed above under known gaps.
    • The final round found no wrong results and no readability regressions.
  • Conversion time on the reviews' test files is equal to or better than at the start of the branch.
Fix https://github.com/icsharpcode/CodeConverter/issues/1211 I think the implication is that we're blindly using inferred array type without checking the actual type of the items that go in, and the user has a Key type with an implicit conversion or something, but the array gets inferred as a string array which can't be turned into a key array
It looks like there are a lot of known gaps. For each one, assess whether a smallish improvement would fix it. Rather than just fix one bug _report_ we're aiming to cover areas of functionality rather than leave holes all over the place

🤖 Generated with Claude Code

https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL

…defined conversion

Fixes icsharpcode#1211

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…hoosing explicit array type

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…dy has the target element type

Replaces the operation-based user-defined-conversion check with a type comparison, which also fixes Object() targets (e.g. {1, 2} previously gave a non-compiling int[]).
Document in CONTRIBUTING that type/symbol APIs are preferred over IOperation for performance.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…s back to their VB type

C# promotes byte/short operands of these operators to int, VB keeps the type, so e.g. Byte() = {b And b} produced a non-compiling int[].

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…the bitwise complement kind

Not on Byte? gave the logical !, which doesn't compile. The numeric case also built a LogicalNotExpression node with a ~ token, so the syntax tree didn't mean what its text says (the harness reported CS0023 for it).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…here the consumer would see the C# int

C# promotes Byte/SByte/Short/UShort operands to int, VB keeps the type. The analyzer only treated the result as int when checking the conversion to its target, so a widening target looked like identity: Dim i As Integer = Not b1 gave ~b1 (-201 rather than 55), b1 << 3 to Long wasn't truncated, b1 Or b2 to Object boxed an int, and a lambda returning b1 And b2 didn't compile. Nullable operands (Byte?) weren't handled at all.

The cast is now added where the operator is converted, based on its consumer (SmallIntegerOperatorPromotion):
- an operand of a wrapping operator of the same type needs none, since that operator's result is cast (no more (byte)((byte)(b1 & b2) & b2));
- a result that's already in range (e.g. And/Or/Xor of in-range operands, signed Not, Mod) needs none where an int means the same: an operand of another intrinsic operator (so (b1 And b2) = b1 has no cast), widening to Integer/Long/floating, String or Boolean;
- anything else (the VB type itself, Object, enums...) gets the cast, unchecked for a constant that C# would reject.

Changed expectation: ValueTupleConstructorBecomesTupleLiteral... Short s * s to an Integer element was s * s, which differs from VB once the product leaves Short's range; it's now (int)(short)(s * s) (the (int) keeps the tuple element type).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…pound

The non-compound result type was taken from the shift count (always Integer), so b1 <<= 1 looked like it needed a cast and became b1 = (byte)(b1 << 1), and l <<= i became l = l << i. A shift's result has its left operand's type, and C# casts a compound shift's result back to it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…its of the shifted type

VB masks the count with 7 for 8-bit and 15 for 16-bit types, C# masks it with 31 after promoting to int, so e.g. a Byte of 200 << 9 gave 0 rather than 144. A constant count is folded to its masked value and left as is when already in range.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ed operators returning one

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
Whether an operator needs a cast depends on whether its operands' values are in range, which depended on them again, twice per level, so a chain of 22 Mods took 47 s to convert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…f C# would get it out of range

(Not C1) * C2 + us on UShort left ~C1 to the wrapping parent's cast, but C# folds the constant -65535 * 40000 and rejects the overflow (CS0220). An out-of-range constant (only Not on an unsigned type and << can give one, since VB rejects any other constant overflow) is now cast unchecked where it is, and a constant with exact operands counts as in range, so (Not C1) * C2 to Integer needs no further cast.

The simplifier kept every ancestor of a cast inside unchecked(...) unsimplified, leaving e.g. (int)(((unchecked((byte)~CB))) % b). That protection is only needed for the Roslyn bug with a cast literal (unchecked((int)0x80000010)), so it's now limited to that.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
VB converts it as a Return statement would, so Function() i as Func(Of Byte) (Option Strict Off) gave () => i, which doesn't compile. Multi-line lambdas already got the conversion through their Return statements. Expression trees are left alone: there, e.g. Object comparisons become C# operators that already give the return type, which the VB types don't show.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ed to another numeric type

The consumer's type was the operand's own converted type, which for an explicit conversion (CByte, CInt, CType) is just its type, so CInt(b1 And b2) gave (byte)(b1 & b2) and CByte(s1 And s2) gave (byte)(short)(s1 & s2). The target of an explicit conversion now counts, and:
- an in-range value converted to any other numeric type needs no cast back, since converting the int gives the same (CInt(b1 And b2) -> b1 & b2, Dim k As Short = b1 And b2 -> (short)(b1 & b2));
- any value converted to an integral type no wider than its VB type needs none either, since that conversion truncates it anyway (CByte(Not us) -> (byte)~us, Dim h As SByte = b1 And b2 -> (sbyte)(b1 & b2)).
For those, the conversion to the target is told the source is an int again, as before this branch, so it adds the one cast.

The docs now say which targets are accepted and why, and the unary minus case covers any operand of another type (e.g. Boolean), not just unsigned ones.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…gral constant count

The binary shift took the mask from the left operand's converted type and the compound shift from the left operand's type, so a Byte enum's e << n was masked but e <<= 9 wasn't. Both now use the type that is shifted, an enum being shifted as its underlying type. A compound shift of an enum also shifts the underlying value now, since C# can't shift an enum (en <<= 9 gave en <<= 9, CS0019; 5347f29 gave en = (E)(en << 9), also CS0019).

A constant count of any integral type is folded (b << 9L, b << Nine), and a count already masked by a constant And within range (n And 3) isn't masked again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…) or an unformatted interpolation

If(nb1 And nb2, 0) converts the value to the If's type (Integer), not the operand's own Byte?, so (byte?)(nb1 & nb2) ?? 0 cast for nothing. An interpolation boxes the value, but without a format string an in-range int formats the same; with one it may not (a negative SByte as :X), so that keeps the cast.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… small integer type back for the setter

Since compound shifts take the shift's own type as the result type (c9aefb8), Q(1) <<= n on a Byte property gave set_Q(1, get_Q(1) << (n & 7)), which doesn't compile: a C# compound operator casts the promoted int back, a setter call doesn't (5347f29 gave set_Q(1, (byte)(get_Q(1) << n))). Q(1) += b had the same problem already at 5347f29. The setter's argument now converts from the type C# gives the operator, int.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…rries bits out of its type

Every constant << was treated as possibly out of range, so Const K1 As Byte = CB1 << 1 got an unchecked cast, which the simplifier then reduced to a bare unchecked(CB1 << 1). The shift's C# value is now compared with VB's. Also:
- a shift whose constant count is masked to 0 (1US << 16) is just its left operand;
- an unchecked cast doesn't nest another unchecked inside it (unchecked((ushort)~(ushort)~1)).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…xpression trees too, but not a nested lambda

The conversion added in 3f3e3e0 wrapped a nested lambda returned as a delegate in a delegate creation (() => new Func<int>(() => 1), was () => () => 1); C# infers the nested lambda's type from the return type, so it's left alone unless the return type isn't a delegate (e.g. Object). Expression trees were skipped entirely, leaving Expression(Of Func(Of Byte)) = Function() i as () => i (CS0266); only an Object comparison is skipped there now, since it becomes a C# comparison that already gives bool.

Tests pin the body conversion for Object, async, String, enum, Decimal, Char, Date and Byte returns, expression trees, LINQ query operators, Queryable lambdas and anonymous type members.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…alue or to an enum no wider

CByte(nb + nb) gave (byte)(byte?)(nb + nb) and CType(b1 And b2, EB) gave (EB)(byte)(b1 & b2) (5347f29: (byte)(nb + nb), (EB)(b1 & b2)). Converting a nullable to its value, or to an enum whose underlying type is no wider, truncates the int as the cast back would, so it now converts the int directly. A wider enum (CType(Not b, DayOfWeek)) still needs the cast back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…o Long

VB's Not converts a fractional operand to Long (rounding to even) first, C# has no ~ for it: Not d gave ~d and Not nd gave ~nd since 7f0284a (!nd before), neither compiles. The operand now gets its VB conversion, e.g. ~(long)Math.Round(d).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ger cast, and document named shift counts

NeedsCastToVbType cached under the unparenthesized node but analyzed the node it was given; both give the same answer, now it's visibly the same node. The shift count docs say a named constant count out of range is folded to its masked value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…onstants

Merging every nested unchecked (7a93d4a) also unwrapped unchecked((int)0x80000010), whose cast nothing protected from the simplifier any more, so the literal became a uint and Not CByte((&H80000010 \ 3) And &HFF) gave 79 instead of 164. Only the unchecked contexts this conversion adds are merged now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… to Boolean

With Option Strict Off, rows.Where(Function(r) r = 5) gave r => Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(r, 5, false)) since 3f3e3e0, which LINQ providers can't translate. VB types an Object comparison (and Not, AndAlso, OrElse of one) as Object, but it converts to a C# expression that's already bool, in or out of an expression tree, so no conversion is added for it. And, Or and Xor of Objects still convert, since they become Operators.AndObject etc.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… integral type

VB converts it at compile time, rounding to even, so Const L1 As Long = Not D, Optional x As Long = Not D and Case Not D are constants; (long)Math.Round(D) isn't (CS0133, CS1736, CS9135). A literal also came out with its fractional text and the target's suffix, e.g. Dim x As Long = 2.5 gave (long)Math.Round(2.5L), which doesn't compile (CS0121). Now ~2L and 2L. A calculated constant keeps its Math.Round form, so the calculation stays visible.

Changed expectation: TestInferringImplicitGenericTypesAsync, CInt(1.0) etc. were (int)Math.Round(1.0d), now 1 (same value). System is no longer used there, so its unused Imports System is dropped from the input, since the comment checker can't find a home for its comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…left side with VB's conversion

VB shifts Boolean as Short, and Single, Double, Decimal and String as Long (with Option Strict Off), but the compound shift took the left side's own type as the shift's, so bo <<= 1, d <<= 2 etc. stayed compound, which C# rejects (CS0019; 5347f29 gave d = (double)(d << 2), also CS0019). The left side is now converted to the type VB shifts it as, as for an enum before, and the count is masked for that type (bo <<= n masks with 15).

Also, a constant shift of True counted True as 1 rather than VB's -1, so True << 3 got a needless unchecked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…wider enum or switched on

CType(b1 Or b2, ES) with a Short-based enum gave (ES)(byte)(b1 | b2), and Select Case b1 And b2 gave switch ((byte)(b1 & b2)) (5347f29: (ES)(b1 | b2), switch (b1 & b2)). An enum target now counts as its underlying numeric type, and each case compares with the value, which an in-range int has just the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…parison body check

TypeOf is always Boolean in VB, so it never reaches the Object-typed body check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… that constant

4e41f1d folded by the VB node's constant value, but a compound assignment converts all of `lhs op rhs` against its right operand, so i += 2.5 became i = 2 (VB 12), and Q(1) += 2.5 became set_Q(1, 2). The fold now also requires the C# node to be that literal or name.

An array bound was converted after adding one, so the fold made Dim c(D) (D = 4.4) new int[4] rather than 5. VB converts the upper bound to Integer first, so that now happens before adding one; that also fixes Dim a(2.5), whose length was Round(3.5) = 4 rather than VB's 3, already at 5347f29.

Changed expectation: ArgumentsAreTypeConvertedAsync, New Single(7 / someInt) {} was new float[(int)Math.Round(7d / someInt + 1)], now new float[(int)Math.Round(7d / someInt) + 1], which matches VB for a bound ending in .5.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…wn type

For If(x, y), the If's type counted as the target, so for If(Not nb, CByte(0)) Byte? to Byte looked like a conversion that truncates, but C#'s ?? converts neither operand: ~nb ?? 0 gave -201 rather than 55, boxed an Int32, picked an Integer overload, and Dim v = If(nb And b2, CByte(0)) didn't compile (from 31a2517 and 8db00f9). A coalesced operand now only skips the cast where the If's type is another, wider type, e.g. If(nb And b2, 0) as Integer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
C# only has + and - of an integer on enums, so x *= 3 (or /=, \=, and
+= or -= of another enum or of an integer its underlying type doesn't
hold) gave CS0019, e.g. x = (E)(x * 3). The enum is now converted to
the operator's type, as x = x * 3 already is: x = (E)((int)x * 3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
A left-side operand that calls anything may call a lambda created
earlier in the method, which can change a local or parameter an earlier
operand reads, e.g. h.Item2(i, f()) += 10 where f sets i. Such a local
or parameter is now captured first when any lambda in the method
captures it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
The temporary passed for an omitted Optional ByRef Object parameter was
given its default as a C# literal, so CByte(True) became the Int32 255
where VB passes the Byte 255. A Byte, SByte, Short or UShort default is
now cast to its type, as the declaration's DefaultParameterValue is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…constant

Each element of an array passed to an attribute must be a C# constant,
but only the argument as a whole was converted as one, so an Object
element such as CByte(True) became Conversions.ToByte(true) (CS0182).
Each element now keeps VB's value and type, e.g. (byte)255.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…n scope

The tuple pattern for lifted ^ matched each Nullable operand by the VB
operand's underlying type, but the C# operand's type often differs, e.g.
int? for a Short? Mod or int for CType(3, Double?) (CS8121). A Nothing
operand matched var, so the null went on to throw. Each operand that may
be Nothing is now matched with { }, binding the C# operand's own type,
and the arm converts it to Double as before; Nothing gives Nothing.

The pattern variables (and the other argN variables of lifted operators)
are named to avoid locals in scope and in the containing block, such as
a user's own arg1 (CS0128).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
C# adds an int constant to an enum only where it fits the underlying
type, and never adds a long, uint or decimal operand, so e.g. e += 1000
or e += -1 on a Byte enum, e += 1L on an Integer enum, or e += 1 on a
ULong enum (a Decimal operation in VB) gave CS0019. Those now convert the
enum to the operator's type, as other operators do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
A query's clauses are lambdas, so a query created earlier can change a
local it captures when a later left-side operand runs it, and a call can
change a Static local by calling the method again. Such a local is now
captured first, as one a lambda captures already is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ocals

A pattern variable in a block's header (If, ElseIf, Do While, Loop
Until, Select Case, Case Is, For Each) is in scope throughout the C#
block's body, so a local of the same name there gave CS0136. A header's
names now avoid the names declared in the block it heads, as a
statement's do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
VB treats a constant Nothing as Nothing whatever its type, e.g.
DirectCast(Nothing, Object), CObj(Nothing), TryCast(Nothing, Object),
DirectCast(Nothing, String) or a Const c As Object = Nothing, and lifts
^ to Double? for it, giving Nothing. The C# gave 1 or 0, and x ^= or
x += such a Nothing was bound late and threw or kept x. Such an operand
is now a typed default(double?) in the lifted pattern, which also fixes
(Nothing), whose bare default had no type (CS8716), and isn't bound late
in a compound assignment.

Converting Const c As Object = Nothing also threw, since its constant
has no type to convert by.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… VB lifts it

4602f0b stopped binding late every compound assignment of a constant
Nothing typed as Object, but the late-bound operator was right for most
left sides: a structure's operator takes Nothing as its default value
(the typed path cast null to it and threw), integral /= overflows as VB
does, and a Date or a concatenation throws as VB does. Only arithmetic
on a Nullable number, Boolean or enum, which VB lifts to give Nothing,
now takes the typed path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…e block's locals

The header of an ElseIf, Case or Catch part is a statement whose parent
(ElseIfBlock, CaseBlock, CatchBlock) isn't, so the search for the block
it heads stopped at the header, and its pattern variables could clash
with a local in that part or a later one, e.g. the Else body (CS0136).
The search now continues to the executable block (If, Select, Try).

Each such case is now in a file of its own, since in a shared file the
generated names are numbered on from earlier functions' and may miss the
clash: ElseIfCond and CaseIs move out of PatternVariableHeaderScopeTests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
A Step expression that may evaluate differently (e.g. calls a function)
was written into both the condition and the increment, so it ran on every
iteration, twice, and any pattern variables it declares clashed (CS0136).
Like the To expression, it's now evaluated once into a loopStep variable.

ContrivedFuncInferenceExampleAsync's New Blah() step changes accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
For s &= n with a Nullable n, VB leaves n's type as it is, so the right
side's converted type isn't the operator's, and the left side was
converted to it: s = Conversions.ToString((Conversions.ToInteger(s) + n).Value),
a numeric addition that throws for "a". The operator's type for & is
String, giving s += n as s = s & n converts to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…m Nothing

(Nothing) wasn't recognised as Nothing when converting it, so it stayed
an untyped default, which C# can't apply an operator to (CS8310), e.g.
d += (Nothing). And where a compound assignment's result is converted
back with its type forced, a Nothing right side made it a cast whatever
the types: t += Nothing on a Date cast a String to DateTime (CS0030),
and is now Conversions.ToDate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
78e6e56 guessed from the operand types, binding late every constant
Nothing typed as Object outside Nullable arithmetic, so &= on a Nullable,
a Nullable structure's lifted operator and String += Nothing gave the
late-bound result where VB binds to the other operand's type. VB treats a
constant Nothing as Nothing whatever its type, which the bound operation
shows: it operates on Object only when bound late, so that now decides.

The typed path then has to give what VB's static binding gives:
- a constant Nothing converted to a structure is its default (a cast of
  null threw), including through VB's own conversion, e.g. Date & Nothing
  converts it to a Date first;
- & turns a Nullable's Nothing into an empty string rather than taking
  its value;
- / of an Object Nothing into an integer stays late-bound, which gives the
  same Double, since its conversion back keeps VB's overflow check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
VB evaluates From, To and Step once each, in that order. 40b1670 only
extracted a Step that may evaluate differently, and put it in the loop's
declaration typed as the control variable even for an enum, whose step
is an integer (CS0266, CS0019), and before the loop ahead of From
where the control variable is declared outside it. Now:
- every non-constant Step is extracted, as To is, since even a local
  or the control variable itself may change in the loop;
- where both can't go in the loop's declaration, To and Step are
  declared before the loop, after From (assigned, or extracted as
  loopFrom) when From may have side effects.

ForEnumAsync, ForVariableStepAsync and ExternallyDeclaredLoopVariableAsync
change accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… does

C#'s + gives a DateTime's own format and an enum's name, where VB's &
gives its Date format and an enum's number, so a Nullable Date or enum
concatenated (as & or &=, which 03c9608 made a C# +) is now converted as
its boxed value: Conversions.ToString(d). Other types' strings match.

c &= "z" on a Char kept C#'s +=, which can't add a string to a char
(CS0029): a string literal converted back to Char was taken for a
constant that becomes a char literal, though its type was forced to the
operator's String.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…e late

The bound operation is only needed where an operand is Object, so other
compound assignments no longer pay for looking it up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
4cfd276 made every constant Nothing converted to a structure its default,
but a String Nothing (CStr(Nothing), DirectCast(Nothing, String), a
String Const) converts as a string in VB, which throws for a Boolean or
a Date. And where a Conversions method converts the Nothing (e.g.
Conversions.ToInteger(ObjC)), it already gives the default and keeps the
constant's name. Now only an Object Nothing converted to a structure
without one (whose cast threw), or through one (e.g. Date & Nothing),
becomes its default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…t reads

VB evaluates From, To and Step into temporaries, then assigns the
control variable. 5f80ccb assigned an outside control variable From
before To and Step were evaluated, so a To or Step reading it saw the
new value (For i = F() To i + 2), and left From in the declaration of an
enum control variable whose To and Step moved before the loop, so it was
read after a To that changes it (e.g. a field it sets).

Where To or Step is extracted before the loop, From now goes in a
loopFrom variable ahead of them, unless it's a constant or none of them
has side effects. That also fixes an outside control variable whose
From (a field, a ByRef or captured local) a To call changes.

ExternallyDeclaredLoopVariableAsync and ForEvaluatesFromToAndStepOnceInOrderAsync
now assign the control variable loopFrom in the loop's initializer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
& kept an enum unconverted where both operands' enum types are the same
ignoring Nullable, as for comparisons, so e & ne gave the enum's name and
e & e didn't compile (CS0019). An enum is now converted to its number
for &, as for arithmetic. And a Nullable left operand of & was converted
to String through its value, which throws for Nothing, where VB gives an
empty string: it's now converted as its boxed value.

Issue590EnumConvertsToNumericStringAsync now compiles, giving
((sbyte)RankEnum.First).ToString() + ((sbyte)RankEnum.Second).ToString().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… change it

A local or parameter Step that the loop body doesn't write (directly,
ByRef or in a lambda), that no lambda captures, and that isn't the
control variable, has the same value at every iteration, so it needn't
be copied to loopStep. ForEnumAsync and ForVariableStepAsync are back to
their outputs before 40b1670.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ange

3121369 left any parameter Step in place, but a ByRef parameter can be
changed through what it refers to (a field the body sets, or another
ByRef parameter for the same variable), so only a local or ByVal
parameter counts now. A Step that needs converting (e.g.
Conversions.ToInteger(s)) is extracted too, rather than converted twice
per iteration.

64fb303 extracted From to loopFrom whenever From, To or Step had side
effects. From now stays in place unless it must be evaluated before To
and Step: when it has side effects, or they do and could change what it
reads (it isn't a local or ByVal parameter they don't write and no
lambda captures). An outside control variable is then assigned before
the loop, unless To or Step could read it (they name it, or it isn't
such a local), when From goes in a loopFrom variable. loopFrom is
declared with var, like loopTo.

ForEnumAsync now extracts its converted (int)step, and
ExternallyDeclaredLoopVariableAsync and ForEvaluatesFromToAndStepOnceInOrderAsync
assign the control variable before the loop again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…rt as before

524d9ee converted any Nullable left operand of & to its boxed string,
but where the other operand is a String, C#'s + already gives an empty
string for null, so only an enum or Date still needs it there.

7f4e988 kept a Conversions method for every constant Nothing typed as
Object, e.g. Conversions.ToInteger((object)null) for DirectCast(Nothing,
Object). That only helps a named constant, which keeps its name; other
forms are the default again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…tep throws

1d5e7a2 assigned an outside control variable From before the loop
whenever To and Step don't name it, but VB only assigns it once To and
Step are evaluated, so where one throws and the exception is caught, the
variable kept From's value rather than its own. From now goes in a
loopFrom variable there too, but only where it could be seen: To or Step
may throw (it isn't free of side effects) and the control variable is
read outside the loop. So For i = F() To G() stays short where i is the
loop's alone.

A Step converted by a cast that can't throw, an enum to its underlying
type or a widening numeric conversion of a local the loop doesn't
change, is left in place as its bare name is, so ForEnumAsync is back to
its earlier output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
a170308 put From in a loopFrom variable wherever To or Step may throw
and the control variable is read outside the loop. But without a Try
around the loop or On Error in the method, the exception leaves the
method, so nothing sees the early assignment: For i = LBound(a) To
UBound(a) keeps i = Information.LBound(a) again. The data-flow analysis
is now only run where a handler could, which also removes its cost.

A function's return variable as the control variable is read when the
function returns, and a Nullable To or Step converted to a value type
throws for Nothing, so both now count.

ForFromIsOnlyExtractedWhereToOrStepCouldChangeOrReadItAsync's i is back
in its F() To F() loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
@GrahamTheCoder GrahamTheCoder changed the title VB -> C#: Use explicit array type unless every initializer item already has the target element type VB -> C#: Compound assignment evaluation order fix and typing improvements for arrays and small integers Nov 28, 2026
@GrahamTheCoder GrahamTheCoder changed the title VB -> C#: Compound assignment evaluation order fix and typing improvements for arrays and small integers VB -> C#: Evaluation order and typing improvements for loops, arrays and small integers Nov 28, 2026
@GrahamTheCoder
GrahamTheCoder merged commit 6f18d26 into icsharpcode:master Nov 28, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

VB -> C#: Collection Initializers/Collection Expressions

2 participants