mika mika - 1 year ago 94
ASP.NET (C#) Question

Parse String to Integer (come hell or high water)

I need to maintain a legacy VB.NET web application. Data typing is, I would say, inconsistent. Especially, there are data that is stored sometimes as integers and sometimes as strings, and I have to parse strings to integers reliably. If parsing goes wrong it should always return 0.

The problem is, I can't use any of the .NET/VB.NET parsing functions for this, but I have to rely on a self-made function.

Could I use a one-liner standard framework call to do every String-to-Integer parsing task?

Let's say there is a string that can be null, empty, contain an integer representation like "10" or contain something else.

I have tried these with an empty input string "":

CType(string, Integer) -> Conversion from string "" to type 'Integer' is not valid.
Convert.ToInt32(string) -> Input string was not in a correct format.
Integer.Parse(string) -> Input string was not in a correct format.
CInt(string) -> Conversion from string "" to type 'Integer' is not valid.
Val(string) -> Success!

But even Val can fail. The surefire way is to call a self-made function:

Public Function ToInteger(ByVal s As String) As Integer

s = Trim(s)
Dim i As Integer

i = Val(s)
Catch ex As Exception
i = 0
End Try

Return i

End Function

I think this sucks. This is bad because:

  • I'm trying to parse strings to integers! This is not rocket science, even if semantics are involved

  • Self-made standards do not stick very well. Somewhere in the code you will always find broken standard framework solutions

As a result there are unnecessary bugs in the software. And I accuse the standard framework for this. Unless, of course a better solution is found :)

Thanks for all the answers. Int32.TryParse is perfect here.

But if you have to cast the input to a string first, the cast can fail. Like when reading from a database object with a possible DBNull value.

Answer Source

Use Int32.TryParse and ignore the return value - just use the value in the out parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download