Search code examples
c#.netcoding-style

What are the best practices for safely parsing a string?


what are the best practices for type conversions in C# ?

   int temp=System.ConvertToInt32(Request.QueryString["Id"]);
    if (temp!=null)
      { // logic goes here }

This fails if Id somehow turns out to be 'abc'

Please advice the use of of ternary operators and other single line statements apart from if else statements (like using single line ternary operators). Also, do you guys prefer TryParse over Convert & why so ? Have your say fellows.


Solution

  • 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 :)