From d8bc1e16d34efae68373b736cc8704977e540bec Mon Sep 17 00:00:00 2001 From: lyn1dev <78355114+lyn1dev@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:03:17 +0100 Subject: [PATCH 1/2] Truncate towards zero when casting a fractional number to an integer - fixes #1021 --- CHANGELOG.md | 1 + CodeConverter/VB/NodesVisitor.cs | 22 +++++++- .../CSToVB/TruncatingCasts.cs | 27 ++++++++++ Tests/VB/SpecialConversionTests.cs | 2 +- Tests/VB/TypeCastTests.cs | 54 ++++++++++++++++++- 5 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 953c2cfd7..62d640b16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### C# -> VB * Don't emit Me on the first parameter of an extension method - [#1118](https://github.com/icsharpcode/CodeConverter/issues/1118) +* Truncate towards zero when converting a fractional number to an integer, instead of inheriting VB's rounding - [#1021](https://github.com/icsharpcode/CodeConverter/issues/1021) ## [10.0.2] - 2026-11-08 diff --git a/CodeConverter/VB/NodesVisitor.cs b/CodeConverter/VB/NodesVisitor.cs index 9e949784c..cc18974bf 100644 --- a/CodeConverter/VB/NodesVisitor.cs +++ b/CodeConverter/VB/NodesVisitor.cs @@ -1442,8 +1442,16 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio Func toNumber = kind => { if (sourceType?.SpecialType == SpecialType.System_Char) return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(Microsoft), nameof(Microsoft.VisualBasic), nameof(Microsoft.VisualBasic.Strings.AscW))), ExpressionSyntaxExtensions.CreateArgList(expr)); - return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), expr); + var operand = destType.IsIntegralType() ? TruncateFractionalSource(expr, sourceType) : expr; + return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), operand); }; + + // The C# compiler has already truncated the operand, and a method call can't appear in a constant expression + var constantValue = _semanticModel.GetConstantValue(node); + if (destType.IsIntegralType() && sourceType.IsFractionalNumericType() && constantValue.HasValue) { + return _commonConversions.Literal(constantValue.Value); + } + switch (destType.SpecialType) { case SpecialType.System_Object: return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CObjKeyword), expr); @@ -1484,6 +1492,18 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio } } + /// + /// C# truncates towards zero when converting a fractional number to an integer, whereas VB rounds. The cast is kept + /// around the call because it fixes the type of the expression (e.g. when it is boxed); the VB simplifier removes it + /// wherever the target type converts implicitly. + /// + private static ExpressionSyntax TruncateFractionalSource(ExpressionSyntax expr, ITypeSymbol sourceType) + { + return sourceType.IsFractionalNumericType() + ? SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(System), nameof(Math), nameof(Math.Truncate))), ExpressionSyntaxExtensions.CreateArgList(expr)) + : expr; + } + public override VisualBasicSyntaxNode VisitObjectCreationExpression(CSSyntax.ObjectCreationExpressionSyntax node) { return SyntaxFactory.ObjectCreationExpression( diff --git a/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs b/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs new file mode 100644 index 000000000..19f0a768b --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs @@ -0,0 +1,27 @@ +using Xunit; + +public partial class TruncatingCasts +{ + [Fact] + public static void TruncatesTowardsZero() + { + double positive = 0.6d; + double negative = -0.6d; + double aboveOne = 1.9d; + decimal decimalValue = 2.9m; + + Assert.Equal(0, (int)positive); + Assert.Equal(0, (int)negative); + Assert.Equal(1, (int)aboveOne); + Assert.Equal(-1, (int)-aboveOne); + Assert.Equal(0, Truncated(negative)); + + long truncatedDecimal = (long)decimalValue; + Assert.Equal(2L, truncatedDecimal); + } + + private static int Truncated(double value) + { + return (int)value; + } +} diff --git a/Tests/VB/SpecialConversionTests.cs b/Tests/VB/SpecialConversionTests.cs index c38ece9e7..5c4346f5d 100644 --- a/Tests/VB/SpecialConversionTests.cs +++ b/Tests/VB/SpecialConversionTests.cs @@ -33,7 +33,7 @@ internal partial class TestClass }", @"Imports System Friend Partial Class TestClass - Private GENERIC_READ As Integer = Math.Pow(46341, 2) + Private GENERIC_READ As Integer = Math.Truncate(Math.Pow(46341, 2)) End Class WARNING: Expression at character 85 contained the checked keyword before conversion"); } diff --git a/Tests/VB/TypeCastTests.cs b/Tests/VB/TypeCastTests.cs index aad004b08..ff716ab13 100644 --- a/Tests/VB/TypeCastTests.cs +++ b/Tests/VB/TypeCastTests.cs @@ -211,4 +211,56 @@ Public Sub TestMethod(o As Object) End Sub End Class"); } -} \ No newline at end of file + + [Fact] + public async Task CastFractionalToInteger_TruncatesTowardsZeroAsync() + { + await TestConversionCSharpToVisualBasicAsync( + @"using System; + +public partial class A +{ + public static void Main() + { + double foo = 0.6d; + int bar = (int)foo; + int baz = (int)Math.Ceiling(foo); + Console.WriteLine(bar); + Console.WriteLine(baz); + } +}", + @"Imports System + +Public Partial Class A + Public Shared Sub Main() + Dim foo = 0.6R + Dim bar As Integer = Math.Truncate(foo) + Dim baz As Integer = Math.Truncate(Math.Ceiling(foo)) + Console.WriteLine(bar) + Console.WriteLine(baz) + End Sub +End Class"); + } + + [Fact] + public async Task CastFractionalToInteger_TruncatedConstantAndBoxedValueAsync() + { + await TestConversionCSharpToVisualBasicAsync( + @"public class A +{ + const int TruncatedConstant = (int)0.6; + void Test(double d, decimal m) + { + object boxed = (int)d; + long fromDecimal = (long)m; + } +}", + @"Public Class A + Const TruncatedConstant As Integer = 0 + Private Sub Test(d As Double, m As Decimal) + Dim boxed As Object = CInt(Math.Truncate(d)) + Dim fromDecimal As Long = Math.Truncate(m) + End Sub +End Class"); + } +} From 7405027893cb196e6e86d57a1f98e06fd22f5d6d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:35:00 +0000 Subject: [PATCH 2/2] Keep the destination type of a folded fractional-to-integral cast The constant path returned a bare literal, so e.g. `object o = (long)2.5;` became `Dim o As Object = 2`, boxing an Integer instead of a Long. Route the folded constant through the same cast as the non-constant path; the simplifier still drops the cast where it's redundant (e.g. Const initializers). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019FEr8GNqY4EeHaJnrFj4NL --- CodeConverter/VB/NodesVisitor.cs | 29 ++++++++++++++--------------- Tests/VB/TypeCastTests.cs | 2 ++ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/CodeConverter/VB/NodesVisitor.cs b/CodeConverter/VB/NodesVisitor.cs index cc18974bf..f988e5ea1 100644 --- a/CodeConverter/VB/NodesVisitor.cs +++ b/CodeConverter/VB/NodesVisitor.cs @@ -1439,19 +1439,15 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio var sourceType = _semanticModel.GetTypeInfo(node.Expression).Type; var destType = _semanticModel.GetTypeInfo(node.Type).Type; var expr = (ExpressionSyntax)node.Expression.Accept(TriviaConvertingVisitor); + if (destType.IsIntegralType() && sourceType.IsFractionalNumericType()) { + expr = TruncateFractionalSource(node, expr); + } Func toNumber = kind => { if (sourceType?.SpecialType == SpecialType.System_Char) return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(Microsoft), nameof(Microsoft.VisualBasic), nameof(Microsoft.VisualBasic.Strings.AscW))), ExpressionSyntaxExtensions.CreateArgList(expr)); - var operand = destType.IsIntegralType() ? TruncateFractionalSource(expr, sourceType) : expr; - return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), operand); + return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), expr); }; - // The C# compiler has already truncated the operand, and a method call can't appear in a constant expression - var constantValue = _semanticModel.GetConstantValue(node); - if (destType.IsIntegralType() && sourceType.IsFractionalNumericType() && constantValue.HasValue) { - return _commonConversions.Literal(constantValue.Value); - } - switch (destType.SpecialType) { case SpecialType.System_Object: return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CObjKeyword), expr); @@ -1493,15 +1489,18 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio } /// - /// C# truncates towards zero when converting a fractional number to an integer, whereas VB rounds. The cast is kept - /// around the call because it fixes the type of the expression (e.g. when it is boxed); the VB simplifier removes it - /// wherever the target type converts implicitly. + /// C# truncates towards zero when converting a fractional number to an integer, whereas VB rounds. The caller keeps the + /// cast around the result because it fixes the type of the expression (e.g. when it is boxed); the VB simplifier + /// removes it wherever the target type converts implicitly. + /// A cast the C# compiler folds to a constant becomes that (already truncated) constant, since a method call can't + /// appear in a VB constant expression. /// - private static ExpressionSyntax TruncateFractionalSource(ExpressionSyntax expr, ITypeSymbol sourceType) + private ExpressionSyntax TruncateFractionalSource(CSSyntax.CastExpressionSyntax node, ExpressionSyntax expr) { - return sourceType.IsFractionalNumericType() - ? SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(System), nameof(Math), nameof(Math.Truncate))), ExpressionSyntaxExtensions.CreateArgList(expr)) - : expr; + var constantValue = _semanticModel.GetConstantValue(node); + return constantValue.HasValue + ? _commonConversions.Literal(constantValue.Value) + : SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(System), nameof(Math), nameof(Math.Truncate))), ExpressionSyntaxExtensions.CreateArgList(expr)); } public override VisualBasicSyntaxNode VisitObjectCreationExpression(CSSyntax.ObjectCreationExpressionSyntax node) diff --git a/Tests/VB/TypeCastTests.cs b/Tests/VB/TypeCastTests.cs index ff716ab13..d4bd5013d 100644 --- a/Tests/VB/TypeCastTests.cs +++ b/Tests/VB/TypeCastTests.cs @@ -253,6 +253,7 @@ void Test(double d, decimal m) { object boxed = (int)d; long fromDecimal = (long)m; + object boxedConstant = (long)2.5; } }", @"Public Class A @@ -260,6 +261,7 @@ void Test(double d, decimal m) Private Sub Test(d As Double, m As Decimal) Dim boxed As Object = CInt(Math.Truncate(d)) Dim fromDecimal As Long = Math.Truncate(m) + Dim boxedConstant As Object = CLng(2) End Sub End Class"); }