Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safest way to check for integer

Tags:

vb.net

This is probally more of an elegance question than functionality. I am looking for the absolutely safest way to check for an integer from a string and an object,

Using most of the built in functions for this in .net seem to generate a first chance exception, displayed in the Immediate window, and over time they just build up. what are the implications of these exceptions as they don't seem to affect the operation of the system.

Here are my two attempts, both feel clunky and I know there has to be a better way than using VB.IsDBNull and Integer.TryParse... Or am I just being anal.

(to integer from 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

(to 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
like image 395
CodeKiwi Avatar asked Dec 01 '22 12:12

CodeKiwi


1 Answers

Whats wrong with using the Integer.TryParse? Thats what it was made for...

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

}

How is that clunky? (C# not VB i know, but same diff)

EDIT: Added if you want to check from an object as well (since TryParse relies on a string) and im not too sure on how you actually plan to use it. Does that cover your concerns a little since this one method will check for both of your cases?

    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;
    }
like image 193
Rosstified Avatar answered Dec 04 '22 23:12

Rosstified