Continuing in the “What’s cool in 2.0” series, I’ll look at a BCL feature today. Imagine you have a Web form, and one of the values a user has to enter is a double. The not-so-ingenious version to accomplish the task is as follows:
void Button1_Click(object sender, EventArgs e){string val = TextBox1.Text;// I'm sure: it is a doubledouble d = Double.Parse(val);}
What’s wrong? Well, there are several things that could make your application go south, err, throw an exception: the value is null, the value is not a double, the value is out of range for a double (all three conditions are well-documented). So you rewrite your application like this:
double d = 0.0f;try{d = Double.Parse(val);}catch (ArgumentNullException ane){}catch (FormatException fe){}catch (OverflowException oe){}
This is how you would do it in 1.1, unless you first do a sanity check using regular expressions (remember: all input is evil until proven otherwise). So what is wrong here? The point is the exception throwing / catching in itself – it involves a stack walk, which equates to lost performance (especially nasty when we are talking heavy-load Web applications). Wouldn’t it be nice if we could get away without exceptions?
Good news! The BCL data types sport a new method – TryParse. Like the Parse method, it takes the input string as the first parameter. The input is followed by an out parameter, which was the return value of Parse – the return value of TryParse is a simple boolean: did the conversion succeed or did it fail. No exceptions.
The following code snippet shows how easy this is:
double d = 0.0f;if (!Double.TryParse(val, out d)){// handle error condition}
My advice: when porting 1.1 applications to 2.0, make sure that you convert all old Parse code to the new TryParse – your applications will perform and scale a lot better.