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.
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.
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.
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With