Skip to content

Commit 33104bd

Browse files
Fix: Cast Enum to integer when assigning to non-convertible types
- Update TypeConversionAnalyzer to only use EnumCastThenConversion if the target type is not an Enum and does not have a defined Conversions.To method. - Add tests covering the reported issue (implicitly casting Enum to custom struct expecting int) and ensuring Enum-to-Boolean logic remains intact without extra (long) casts. Co-authored-by: GrahamTheCoder <2490482+GrahamTheCoder@users.noreply.github.com>
1 parent 11366b2 commit 33104bd

2 files changed

Lines changed: 35 additions & 3 deletions

File tree

CodeConverter/CSharp/TypeConversionAnalyzer.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,14 @@ public TypeConversionKind AnalyzeConversion(VBSyntax.ExpressionSyntax vbNode, bo
165165
return TypeConversionKind.Identity;
166166
}
167167

168-
if (!vbConvertedType.IsEnumType()) {
168+
if (vbConvertedType.SpecialType == SpecialType.System_String) {
169169
return TypeConversionKind.EnumCastThenConversion;
170170
}
171+
172+
if (!vbConvertedType.IsEnumType() && !ExpressionEvaluator.ConversionsTypeFullNames.ContainsKey(vbConvertedType.GetFullMetadataName())) {
173+
return TypeConversionKind.EnumCastThenConversion;
174+
}
175+
171176
return TypeConversionKind.Conversion;
172177
}
173178

Tests/CSharp/ExpressionTests/ExpressionTests.cs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Threading.Tasks;
1+
using System.Threading.Tasks;
22
using ICSharpCode.CodeConverter.Tests.TestRunners;
33
using Xunit;
44

@@ -2931,7 +2931,6 @@ public object Edit(bool flag2 = false, CrashEnum? crashEnum = default)
29312931
}
29322932
}");
29332933
}
2934-
29352934
[Fact]
29362935
public async Task Issue1211_EnumToCustomTypeImplicitConversionAsync()
29372936
{
@@ -2999,4 +2998,32 @@ public void Foo()
29992998
}");
30002999
}
30013000

3001+
[Fact]
3002+
public async Task EnumToBooleanAsync()
3003+
{
3004+
await TestConversionVisualBasicToCSharpAsync(
3005+
@"Public Class C
3006+
Public Sub M(e As ESByte)
3007+
Dim vBooleanSByte As Boolean = e
3008+
End Sub
3009+
End Class
3010+
3011+
Public Enum ESByte As Long
3012+
M1 = 1
3013+
End Enum",
3014+
@"using Microsoft.VisualBasic.CompilerServices; // Install-Package Microsoft.VisualBasic
3015+
3016+
public partial class C
3017+
{
3018+
public void M(ESByte e)
3019+
{
3020+
bool vBooleanSByte = Conversions.ToBoolean(e);
3021+
}
30023022
}
3023+
3024+
public enum ESByte : long
3025+
{
3026+
M1 = 1L
3027+
}");
3028+
}
3029+
}

0 commit comments

Comments
 (0)