What are the best practices for safely parsing a string?
TryParse
has the obvious advantage that in the case of failure it will return false instead of throwing an exception.
The standard pattern would be something like:
int value;
if (int.TryParse(Request.QueryString["Id"], out value))
{
// Use value
}
else
{
// Do whatever you want on failure
}
Now, it's also worth bearing in mind that you can give int.TryParse
an IFormatProvider
and a NumberStyles
- for example, you may well want to specify CultureInfo.InvariantCulture
as the IFormatProvider
if this is really meant to be an auto-generated ID (rather than one entered by a user).
If you want to effectively have "default values" you could write a helper method like this:
public static int? NullableTryParseInt32(string text)
{
int value;
return int.TryParse(text, out value) ? value : (int?) null;
}
You can then use this like so:
int value = NullableTryParseInt32(text) ?? 10;
Or you could just write a method which takes a default value, of course :)