× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How can I safely downsize a long to an int?

Steven Doggart
Jul 01, 2015
<p>As you can see in the answers to my <a href="http://stackoverflow.com/q/14708778/1359668">related, similar question</a>, there are ways to do that sort of thing, but nothing really more convenient than a simple <code>Try/Catch</code> block. If you want to avoid the inefficiency of a <code>Try/Catch</code> block, I would recommend checking the value first, like this:</p> <pre class="lang-vb prettyprint-override"><code>If (myLongValue &gt;= Integer.MinValue) AndAlso (myLongValue &lt;= Integer.MaxValue) Then myIntValue = CInt(myLongValue) End If </code></pre> <p>Or, if you want to set the value to something specific when it is outside of the range:</p> <pre class="lang-vb prettyprint-override"><code>If myLongValue &lt; Integer.MinValue Then myIntValue = Integer.MinValue ElseIf myLongValue &gt; Integer.MaxValue Then myIntValue = Integer.MaxValue Else myIntValue = CInt(myLongValue) End If </code></pre> <p>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:</p> <pre class="lang-vb prettyprint-override"><code>&lt;Extension&gt; Public Function AsInt32(value As Long) As Integer If value &lt; Integer.MinValue Then Return Integer.MinValue ElseIf value &gt; Integer.MaxValue Then Return Integer.MaxValue Else Return CInt(value) End If End Function </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/26764893/How%20can%20I%20safely%20downsize%20a%20long%20to%20an%20int?/26765110">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus