Trycast for String to Integer in Vb. Net

Trycast for String to Integer in Vb. Net

I do not understand at all how to use TryCast in my code, but it is something I need to use for validating user input. I have done various searches and looked at various questions on here, but no one seems to actually say how to use it, and the MSDN website doesn't seem to help at all.

    Function ValidateInput(Var_In As String) As Integer

        If TryCast(Var_In, Integer) = Nothing Then

            Return vbNull
        Else
            Return Var_In
        End If
    End Function

The error says that

The operand must be of reference type but Integer is of value type

What is the explanation of what I have done wrong?

TryParse doesn't accept more than 10 digits so for example, an input of "12345678901" won't be accepted. How do I fix this?

3

5 Answers

Let's try to understand the differences between TryCast, Convert and TryParse.

TryCast

This function will attempt to convert one object into another type, as long as it is a reference type.

Dim MyNewObject = TryCast(MyObject, MyReferenceClass)
If IsNothing(MyNewObject) Then
    MessageBox.Show("Impossible to cast")
End If

Since Integer is a value type, it will not work, so we have to figure something out...

Convert

Convert Class on MSDN

From MSDN:

Converts a base data type to another base data type.

So we can try:

Dim myInt = Convert.ToInt32(MyObject)

The problem is that it will generate an exception InvalidCastException if it's impossible to do the conversion.

TryParse

This function is trying to convert a String into something you want. And it will not generate an exception:

Dim myInt As Integer = 0
If Not Integer.TryParse(MyString, myInt) Then
    MessageBox.show("This is not an integer")
End If

Limitation

Converting a String into a Integer can sometimes be tricky... If the String represents a number that is greater or lesser than Integer.MaxValue and Integer.MinValue, you will end up with no conversion...

So you can go with a Double:

Double.TryParse(MyString, MyDouble)

Or personally, if you know that it will be a number, use Decimal:

Decimal.TryParse(MyString, MyDecimal)

See Decimals on MSDN

Decimal still has a Max and Min value, according to MSDN:

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors.

Convert.ChangeType

This one is also interesting, but is a bit weird...

2

You are attempting to perform TryCast against an Integer, which is a value type. TryCast works only on reference types, such as (but not limited to) a Class, Object, or String type.

If you are trying to convert the input parameter to an Integer, you might try one of the methods in the Convert class, such as Convert.ToInt32() or Integer.TryParse.

2

Instead of TryCast, use TryParse:

Function ValidateInput(Var_In As String) As Integer
    Dim iNum As Integer
    If (Integer.TryParse(Var_In, iNum)) Then
        Return iNum
    Else
        Return vbNull
    End If
End Function
3

Much better is to use TryParse:

Function ValidateInput(Var_In As String) As Integer   
    Dim num as Integer
    If Not Integer.TryParse(Var_In, num) Then
        Return vbNull
    Else
        Return num
    End If
End Function

I'm late to the discussion, but if anyone lands here (like I did) looking for a quick & dirty solution, here a function I'm using for simple cell validation in a DataGridView control.

Function TryTypeFit(theString As String, theType As Type, ShowError As Boolean) As Boolean
    Dim TempReturn As Boolean = False
    Dim TempObject As Object

    Try
        TempObject = Convert.ChangeType(theString, theType)
        TempReturn = True
    Catch ex As Exception
        ' didn't work
        TempReturn = False

        If ShowError Then
            Dim eMessage As String = "Error: Value must be castable to a " & CStr(theType.Name)
            MsgBox(eMessage)
        End If
    End Try

100: Return TempReturn End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.