Daniel
Daniel

Reputation: 11054

What's the best way to default to 0 if an integer/double cast fails?

I don't like having to do something like this every time I use CInt or Integer.Parse (which I realize is costly):

Try
  someIntVariable = CInt(someStringVariable)
Catch ex As Exception
  someIntVariable = 0
End Try

And I don't like all the lines of code involved with Integer.TryParse. I guess I could create a function that does something like:

Function ToInteger(str As String) As Integer
  Dim number As Integer
  Int32.TryParse(str, number)
  Return number
End Function

But isn't there already an extension method or something built into .NET that can do this for me in a more elegant way (along the lines of Nullable(Of T).GetValueOrDefault)?

Upvotes: 1

Views: 725

Answers (4)

Rose
Rose

Reputation: 641

Maybe this could work for you..

Function ToInteger(str As String) As Integer
    Dim number As Integer
    If IsNumeric(str) Then
        number = CInt(str)
    Else
        number = 0
    End If
    Return number
End Function

Upvotes: 1

avanek
avanek

Reputation: 1659

Honestly Integer.TryParseis the way to go, but you can always hide it behind an extension method if you do not like the syntax.

Public Module IntegerExtensions
    <Extension()> _
    Public Function AsIntOrDefault(ByVal valueToParse As String, Optional ByVal defaultValue As Integer = 0) As Integer
        Dim retVal As Integer = 0

        If Not Integer.TryParse(valueToParse, retVal) Then
            retVal = defaultValue
        End If

        Return retVal
    End Function
End Module

Which can then be used like this:

Public Class Foo
    Public Sub Blah()
        Dim value1 As Integer = "IWillNotParse".AsIntOrDefault() 'Should be 0
        Dim value2 As Integer = "IWillNotParse".AsIntOrDefault(5) 'Should be 5
        Dim value3 As Integer = "123".AsIntOrDefault() 'Should be 123
    End Sub
End Class

Upvotes: 7

Alex Wiese
Alex Wiese

Reputation: 8370

You should not use try/catch if you don't need to. There is a lot of overhead involved in throwing an exception.

Instead you can simply use this code (no if/end if statement)

Dim value As Integer = 0
Int32.TryParse(stringValue, value)

If the string is parse-able then you will have the value, otherwise 0.

Upvotes: 5

Chris Stauffer
Chris Stauffer

Reputation: 352

Try out Integer.TryParse(String, Integer)

You pass the String you want to parse, and the Integer you want to store the result in.

TryParse returns a Boolean with whether the parse succeeded or failed. So you could do

If Not Integer.TryParse(myNonInt, DestinationInt)
    DestinationInt = 0
End If

If the parse succeeds, the value automatically gets stored in DestinationInt.

Upvotes: 0

Related Questions