A common task in many applications is to convert a string value to a number. For example, if a user types a number into a TextBox, the Text property of the TextBox returns a string. But if you want to work with the value as a number, you need to convert it.

There are many ways to accomplish this task:

  • Val(myString)
    VB Only. This function returns the value of the first set of numbers in the string. If the string contains other characters, the evaluation stops at the first non-numeric character. So Val(“10 5th street”) returns 105. A run-time exception is generated if the value is too large or if the parameter cannot be converted to a string.
  • CType(myString, Integer)
    VB Only. This function converts the expression to the specified data type. A run-time exception is generated if the conversion fails.
  • CInt(myString)
    VB Only. This function converts the expression to an integer. It takes an object as a parameter. A run-time exception is generated if the conversion fails.
  • Convert.ToInt32(myString)
    This function converts the expression to an integer. It provides overloads to convert from many different types of values to an integer. A run-time exception is generated if the conversion fails.
  • Integer.Parse(myString) / int.Parse(myString)
    This function converts the expression to an integer. A run-time exception is generated if the conversion fails.

You may have noticed that each of these functions generate exceptions. In many cases, it would be nice to perform the conversion without generating an exception. This is especially important when processing user input because the user could leave the value blank or type in a value that is not numeric.

This is where TryParse comes in handy. It returns true or false defining whether the conversion was successful instead of generating an exception. The TryParse function was new in .NET 2.0.

In C#:

string value  = "10";
int num;

if (int.TryParse(value, out num))
    Debug.Print("Success! Value is {0}", num);
else
    Debug.Print("Please enter a numeric value");

In VB:

Dim value As String = "10"
Dim num As Integer

If Integer.TryParse(value, num) Then
    Debug.Print("Success! Value is {0}", num)
Else
    Debug.Print("Please enter a numeric value")
End If

In both examples, the TryParse takes a string as the first parameter and an integer as an out (By Ref in VB) second parameter. If the conversion succeeds, the second parameter contains the converted value and TryParse returns true. If the conversion fails, the second parameter contains a value of 0 and TryParse returns false.

TryParse is also available for other data types such as Boolean, DateTime, Double, Decimal, and so on.

Enjoy!

Filed under: , , ,

Comments

# re: TryParse

Tuesday, August 11, 2009 9:48 PM by CB

So there is no distinguishing between the user entering '0' and the user entering 'A'??

# re: TryParse

Wednesday, August 12, 2009 10:47 AM by Deborah Kurata

Hi CB -

Thank you for visiting my blog!

You are right in the num will be 0 in both cases. However, if the user enters '0' the If statement will be true. If the user enters 'A', the If statement will be false.

Hope this helps.

# re: TryParse

Thursday, August 13, 2009 1:37 PM by Jon Arild Tørresdal

I prefer implementing TryParse using what in DDD is called a Value Object. I have an example here: blog.torresdal.net/.../RefactoringTryParseIntoAValueObject.aspx

# re: TryParse

Thursday, August 13, 2009 5:17 PM by Deborah Kurata

Hi Jon -

Thanks for the link!

# re: TryParse

Friday, August 14, 2009 4:31 AM by notken

I've written an extension method with the help of the generic code here: theengineroom.provoke.co.nz/.../generic-tryparse-type-conversion.aspx

The idea is that you can implement TryParse on any value type by extending the string type, returning a nullable value type, so you can test if the parse was successful. I hope this code shows up in the comments!

public static class Parsing
{
    public static Nullable<T> Parse<T>(this string tryVal) where T : struct
    {
        Nullable<T> result = null;
        try
        {
            int iNumberOfMethods = typeof(T).GetMethods().Length;
            MethodInfo mTryParse = null;
            for (int iCounter = 0; iCounter <= iNumberOfMethods; iCounter++)
            {
                MethodInfo mCurrent = (MethodInfo)typeof(T).GetMethods().GetValue(iCounter);
                if (mCurrent.Name.Equals("TryParse"))
                    {
                    mTryParse = mCurrent;
                    break;
                    }
            }
            if (mTryParse != null)
            {
                T passIn = default(T);
                object[] args = { tryVal, passIn };
                bool success = (bool)mTryParse.Invoke(null, args);
                if (success)
                    result = new Nullable<T>((T)args[1]);
                else
                    result = new Nullable<T>();
            }
        }
        catch { }

        return result;
    }
}

And this is how you would use it:

[Test]
public void Testing_Parse_Helper()
{
    string ok = "123";
    string notOk = "hello";
    int? try1 = ok.Parse<int>();
    double? try2 = notOk.Parse<double>();
    Assert.IsNotNull(try1);
    Assert.AreEqual(try1, 123);
    Assert.IsNull(try2);
}

# re: TryParse

Friday, August 14, 2009 10:15 AM by Deborah Kurata

Hi Notken -

Thank you for visiting my blog and for your post. The code originally lost all of the formatting, so I had to reformat it. Let me know if I introduced any errors.

Thanks again!

# re: TryParse

Saturday, August 15, 2009 10:37 AM by vamsi

TryParse in java?

# re: TryParse

Thursday, October 29, 2009 8:23 AM by John Dauphine

I found a couple of code posting on a nullable tryparse method.  The code the I came up with is here johndauphine.blogspot.com/.../nullable-tryparse-function-in-c.html.

# re: TryParse

Thursday, October 29, 2009 8:37 AM by John Dauphine

BTW, here is how I call a the function  

NullableParser<double>.TryParse(dataToLoad["foobar"].ToString(),  out  _fooBar );

Where datatoload is a DataRow

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: