A guy on the ASP.NET forums had a question about using Double.TryParse() to convert strings with currency symbols into doubles. As he says in his post, "The arguments that it requires are confusing and I keep getting errors." Completely true. (Test your expertise: read the 1.1 documentation topic on Double.TryParse and see if you get it right the first time.)
[TryParse is like Parse, except it won't throw on an error, it just returns false. If the parsing succeeds, it returns the resulting double in an out parameter.]
I hunted around for an example, but that proved hard to come by. There are no examples in the 1.1 documentation, as noted. An Italian person named Andrea Boschin has a blog entry with an example that proves helpful. The DailyWTF has a post making fun of someone who wrote their own equivalent logic (and a lengthy set of comments upon that), but does not provide an example.
Anyway, I played with it and did up a test page, which I have below.
My research did, however, result in triple-plus goodness for the upcoming 2.0 release. For one, the 2.0 documentation (now in beta) has examples of TryParse, yay. For two, there is now an overload that just takes the string and the out parameter -- none of those complicated flags or culture specifiers. For three, they've added TryParse methods to all the base types, so we can now use them with, say, Boolean and DateTime and TimeSpan and IPAddress (!) and all the rest. Yay for the 2.0 release!
Here's an example for 1.1:<%@ Page Language="VB" Strict="true" %>
<%@ import Namespace="System.Globalization" %>
<style>
body {font-family:verdana; font-size:9pt;}
h1 {font-family:verdana; font-size:12pt; font-weight:bold}
</style>
<script runat="server">
Sub buttonTryParse_Click(sender As Object, e As EventArgs)
Dim result As Double = 0
Dim pass As Boolean = false
' Next line uses a composite flag
'pass = Double.TryParse(TextBox1.Text, NumberStyles.Currency, _
' CultureInfo.CurrentCulture, result)
' Next line uses individual flags OR'd together
pass = Double.TryParse(TextBox1.Text, NumberStyles.AllowCurrencySymbol OR _
NumberStyles.AllowThousands OR _
NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, result)
If pass = True Then
Label1.Text = "Parsing successful, number is " & result.ToString()
Else
Label1.Text = "Number could not be parsed into a double."
End If
End Sub
</script>
<html>
<body>
<form runat="server">
<h1>Double.TryParse Test</h1>
<p>
Enter a number:<br>
<asp:TextBox id="TextBox1" runat="server" />
<asp:Button id="buttonTryParse" onclick="buttonTryParse_Click"
runat="server" Text="Test" />
<br/>
<i>(accepts currency symbol, thousands separators,
decimal point)</i>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>