According to the question, "Can I convert long to int?", the best way in C# to convert a long to an int is:
int myIntValue = unchecked((int)myLongValue);
How can I do this in VB.NET? VB.NET does not have the concept of unchecked to my understanding.
When I convert the code in a converter, it says to use CInt(). But CInt throws a system.overflowexception. Using unchecked in C# prevents a system.overflowexception.
I'd rather not catch the exception.
Dim x As Long = Int32.MaxValue
x = x + 100
Console.WriteLine(x)
Dim y As Integer = CInt(x)
Console.WriteLine(y)
As you can see in the answers to my related, similar question, there are ways to do that sort of thing, but nothing really more convenient than a simple Try/Catch
block. If you want to avoid the inefficiency of a Try/Catch
block, I would recommend checking the value first, like this:
If (myLongValue >= Integer.MinValue) AndAlso (myLongValue <= Integer.MaxValue) Then
myIntValue = CInt(myLongValue)
End If
Or, if you want to set the value to something specific when it is outside of the range:
If myLongValue < Integer.MinValue Then
myIntValue = Integer.MinValue
ElseIf myLongValue > Integer.MaxValue Then
myIntValue = Integer.MaxValue
Else
myIntValue = CInt(myLongValue)
End If
If you wanted to make it more convenient, you could make it a function. If convenience is the ultimate goal, you could even make it an extension method:
<Extension>
Public Function AsInt32(value As Long) As Integer
If value < Integer.MinValue Then
Return Integer.MinValue
ElseIf value > Integer.MaxValue Then
Return Integer.MaxValue
Else
Return CInt(value)
End If
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With