6

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
  • For value types (like int) use Integer.TryParse to validate user input. As the err msgs says, TryCast is for objects/reference types. See Value Types and Reference Types Commented Mar 31, 2016 at 13:49
  • 2
    You dont need a function. Use Integer.TryParse the result will be a boolean telling you if it is a valid int, if it succeeds the value will be assigned Commented Mar 31, 2016 at 13:57
  • 2
    TryParse doesn't accept more than 10 digits ... an input of "12345678901"... won't be accepted Thats because that string cant be stored as an integer. The max value for an int is 2147483647 Commented Mar 31, 2016 at 14:17

5 Answers 5

20

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...

Sign up to request clarification or add additional context in comments.

2 Comments

I like your answer as you took the time to format it and so on. Could you provide an answer for the edit aswell?
Good, researched, well thought out explanation. Thanks!
1

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 Comments

I want to use trycast (or atleast something equivilent to it) so that I avoid any exceptions being thrown. Is there anything like this?
Look at Integer.TryParse
1

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 Comments

So, is TryParse like TryCatch in that it doesn't raise any exceptions? Because that is what Im after
How will the calling code know when the TryParse failed? That will return 1 when it fails.
I don't understand why people use so little whitespace. It annoys me slightly
0

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

Comments

0

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 tempObject As Object
    Dim tempReturn As Boolean = False
    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
    Return tempReturn
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.