The most reliable way to validate an integer

This is more of a more elegant issue than functionality. I am looking for an absolutely safe way to check an integer from a string and an object,

Using most of the built-in functions for this in .net seems to throw the first probability exception displayed in the Immediate window, and over time they simply accumulate. what are the consequences of these exceptions, since they do not seem to affect the operation of the system.

Here are my two attempts: both feel awkward, and I know there must be a better way than using VB.IsDBNull and Integer.TryParse ... Or am I just anal.

(integer from the object)

    Dim nInteger As Integer = 0
    If oData Is Nothing OrElse VB.IsDBNull(oData) Then
    Else
        If bThrowErrorIfInvalid Then
        Else
            On Error Resume Next
        End If
        nInteger = CType(oData, Integer)
    End If
    Return nInteger

(integer from string)

    Dim nInteger As Integer = 0
    If sText Is Nothing Then
    Else
        If bThrowErrorIfInvalid Then
        Else
            On Error Resume Next
        End If
        Integer.TryParse(sText, nInteger) 
    End If
    Return nInteger
+3
source share
6 answers

Integer.TryParse? , ...

int i = 0;
string toTest = "not number";
if(int.TryParse(toTest, out i))
{
   // it worked

}

? (# VB, , diff)

EDIT: , ( TryParse ), , . , ?

    static bool TryParseInt(object o, out int i)
    {
        i = 0;

        if (o.GetType() == typeof(int))
        {
            i = (int)o;
            return true;
        }
        else if (o.GetType() == typeof(string))
        {
            return int.TryParse(o as string, out i);
        }

        return false;
    }
+15

:

Dim i as Integer
Try
    i = Convert.ToInt32(obj)
Catch
    ' This ain't an int
End Try

Convert System.

EDIT: . - Try, , , Catch, , Convert.ToInt32, / - , - try/catch .

+2

Integer.TryParse , : . ToString() TryParse.

On Error Resume Next Try-Catch, - , .

+1

VB, IsNumeric

+1

it looks like in your second example you have an unnecessary check for bThrowErrorIfInvalid, because Integer.TryParse never throws an error. Sort of

If bThrowErrorIfInvalid And Not Integer.TryParse(sText, nInteger) Then
   Throw New ArgumentException()
EndIf
0
source
Dim d As Double = 2.0
Dim i As Integer = CInt(d)
If d - i = 0 Then
     Debug.WriteLine("is integer")
Else
     Debug.WriteLine("not a integer")
End If
0
source

Source: https://habr.com/ru/post/1703715/


All Articles