Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
Zo Has Avatar asked Aug 11 '10 09:08

Zo Has


People also ask

How do you Parse a string?

To parse a string in Java, you can use the Java String split() method, Java Scanner class, or StringUtils class. For parsing a string based on the specified condition, these methods use delimiters to split the string.

What are Parse methods?

Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar.


2 Answers

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

like image 124
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet


When it comes to solving any problem that has several similar solutions I also try to find the one that express to the reader of the code what I'm trying to accomplish the cleæret. In my oppinion that means going for the .TryParse in this particular case.

Using TryParse tells the reader that you are not guaranteed that the input is valid (if you were i'd use parse instead) And since you are actually trying to parse the input as an int you might as well let the code read Line your intentions

like image 35
Rune FS Avatar answered Sep 28 '22 06:09

Rune FS