C# TryParse

Mostly we're using strings to hold text or a branch of characters which may include digits, true/false or date time, etc. Sometimes we'll have to convert a digital string to a numeric data type for further calculation or convert a date time string to a DateTime type and save it in a database. All these conversions can be come true by the TryParse method.

As we know, most data types are structs and include at least a method TryParse to convert a string to their own types. These data types are listed below.

Type.NET Framework TypeTryParse SyntaxDescription
boolSystem.Booleanpublic static bool TryParse(string s, out bool result)Convert the string s to its Boolean equivalent result.
sbyteSystem.SBytepublic static bool TryParse(string s, out sbyte result)Convert the string s to its SByte equivalent result.
byteSystem.Bytepublic static bool TryParse(string s, out byte result)Convert the string s to its Byte equivalent result.
shortSystem.Int16public static bool TryParse(string s, out short result)Convert the string s to its 16-bit signed integer equivalent result.
ushortSystem.UInt16public static bool TryParse(string s, out ushort result)Convert the string s to its 16-bit unsigned integer equivalent result.
intSystem.Int32public static bool TryParse(string s, out int result)Convert the string s to its 32-bit signed integer equivalent result.
uintSystem.UInt32public static bool TryParse(string s, out uint result)Convert the string s to its 32-bit unsigned integer equivalent result.
longSystem.Int64public static bool TryParse(string s, out long result)Convert the string s to its 64-bit signed integer equivalent result.
ulongSystem.UInt64public static bool TryParse(string s, out ulong result)Convert the string s to its 64-bit unsigned integer equivalent result.
floatSystem.Singlepublic static bool TryParse(string s, out float result)Convert the string s to its single-precision floating-point number equivalent result.
doubleSystem.Doublepublic static bool TryParse(string s, out double result)Convert the string s to its double-precision floating-point number equivalent result.
decimalSystem.Decimalpublic static bool TryParse(string s, out decimal result)Convert the string s to its decimal equivalent result.
charSystem.Charpublic static bool TryParse(string s, out char result)Convert the string s to its equivalent Unicode character result.
N/ASystem.DateTimepublic static bool TryParse(string s, out DateTime result)Convert the string s to its DateTime equivalent result.
N/ASystem.TimeSpanpublic static bool TryParse(string s, out TimeSpan result)Convert the string s to its TimeSpan equivalent result.

As you can see all the above TryParse methods are static and return a boolean value to indicate if the conversion succeeded or failed. If succeeded, the out argument will hold the converted data.

Example 01-77-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;

class TestTryParse
{
    static void Main()
    {
        // Boolean value conversion
        bool b;
        string sb = "TRUE";
        if (bool.TryParse(sb, out b))
        {
            Console.WriteLine("b = {0}", b);
        }
        else
        {
            Console.WriteLine("Failed boolean conversion.");
        }
        
        // Integer value conversion
        int i;
        if (int.TryParse("123.8", out i))
        {
            Console.WriteLine("i = {0}", i);
        }
        else
        {
            Console.WriteLine("Failed integer conversion.");
        }

        // DateTime value conversion
        DateTime dt;
        if (DateTime.TryParse("2014/10/30", out dt))
        {
            Console.WriteLine("dt = {0}", dt);
        }
        else
        {
            Console.WriteLine("Failed DateTime conversion.");
        }

        Console.Read();
    }
}

Output

b = True
Failed integer conversion.
dt = 10/30/2014 12:00:00 AM

Explanation

  • Line 10: Try to convert a string "TRUE" to a boolean type. As you see, the conversion succeeded and the out argument b hold the converted boolean value.
  • Line 20-21: Try to convert a string "123.8" to an integer. But the conversion failed and the integer variable i keeps uninitialized. If the code is changed as follows the conversion will succeed.
  • float i;
    if (float.TryParse("123.8", out i))
    
  • Line 32: Try to convert a string "2014/10/30" to DateTime type. Apparently the conversion succeeded and the out argument dt hold the converted DateTime value.
  • Line 34: The DateTime variable dt is printed.

An alternative method to convert a string to another data type is the Parse method. Like TryParse, Parse method also exists in most data types. The only difference between TryParse and Parse is that Parse method will issue an exception at run-time if the conversion failed.

Example 01-77-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class TestTryParse
{
    static void Main()
    {
        // Use TryParse
        TimeSpan ts;
        if (TimeSpan.TryParse("2014/10/30", out ts))
        {
            Console.WriteLine("dt = {0}", ts);
        }
        else
        {
            Console.WriteLine("Failed TimeSpan conversion.");
        }

        // Use Parse
        //ts = TimeSpan.Parse("2014/10/30");

        Console.Read();
    }
}

Output

Failed TimeSpan conversion.

Explanation

  • Line 9: "2014/10/30" cannot be converted to a TimeSpan value so the failed string is printed.
  • Line 19: This line is commented out. If not, you will get an Unhandled Exception error message when the program runs. We'll introduce how to handle exceptions in the later section.

In summary, if the conversion is confirmed to be successful, the Parse method can be used. Otherwise, we'd best use TryParse instead of Parse.