New TryParse method in .net 2

.net 2 introduces new TryParse method for many base structures such as Int32. However, it is not limited to structs only (IPAddress has its own TryParse, too). Why .net 2 introduces this method at all, since we already have Parse method you might wonder? Let’s look at the example how you would use Int32.Parse method:


tring s = “1”;


try


{


int i = Int32.Parse(s);


}


catch (Exception ex)


{


// … deal with bad input


}


This code works, but it is expensive in terms of performance because handling exceptions is always more expensive than handling return values. Also, it is somewhat verbose. That’s why there is TryParse:


string s = “1”;


int i;


bool result = Int32.TryParse(s, out i);


At first glance it is obvious that the code is far more explanatory. Also note that instead of getting an exception if the input is not correct, you get a false value. And TryParse internally doesn’t use exceptions handling mechanisms which make it faster, too. One thing that you might pay attention to, is that you get some sort of value stored into the variable you pass regardless if the operation succeeds or not (the consequence of out keyword). IOW even if there is a conversion error you variable will be set to 0 (in numeric case) and not left as is as in Parse example.


Anyway, the bottom line is that there is no reason for you to not to deprecate Parse and build your code using TryParse instead.

2 thoughts on “New TryParse method in .net 2

  1. IIRC, .net 1.1 already had TryParse method implemented (at least on Double…)

    Double.TryParse Method [C#]

    public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out double result
    );

Leave a Reply