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 aTry/Catch
block, I would recommend checking the value first, like this:Or, if you want to set the value to something specific when it is outside of the range:
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: