views:

118

answers:

7

Hi, 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.

A: 

use the TryParse method of the int class.

int temp;
if (int.TryParse(Request.QueryString["Id"], out temp)
  { // logic goes here }

If id does not contain a number TryParse will return false.

UPDATE: Changed to show int.TryParse

Philip Smith
string doesn't seem to have a tryparse method for me... You sure you weren't meaning to type int.TryParse?
Chris
Isn't the out temp of a concern here ?
Popo
I think you mean to use int.TryParse there is no string.TryParse, after all why would you want to parse a string into a string ;-)
Ben Robinson
+3  A: 

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

Jon Skeet
Hi Jon, thanks for the reply. How would you do that statement with a ternary operator ? Also isn't that 'out' initialized every time I evaluate, match or no match ? Shouldn't we avoid tryParse just because of that ?
Popo
@Popo: Yes, the `out` parameter is initialized either way, but why would you avoid `TryParse` because of that? I've added another couple of options for simplifying this in the case where a default value makes sense - but very often the first form really is the one to go with.
Jon Skeet
Thanks Jon, Would TryParse only return true/false ? Can I check for exceptions in TryParse as Sunrisas did in using Convert ?
Popo
+1  A: 

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

Rune FS
+1  A: 

Hi

You have two ways to do that

int i;
if (Int32.TryParse(Request.QueryString["Id"], out i))
{
}

or you can do:

try
{
     Convert.ToInt32(Request.QueryString["Id"]);
}
catch (FormatException ex)
{
   // The field Id it's not convertible
}
catch (Exception ex)
{
   // It could throw also ArgumentException or OverflowException
}
Sunrisas
Hi sinrisas, how can I catch exceptions in tryParse?
Popo
Well, you can put it into a try catch statement. The only exception TryParse can throw, as far as I know, it's ArgumentException but in this case I suppose you will always pass a string to it, so you'll never get such exception. The idea behind TryParse it's not to use a try catch statement, as it returns true or false depending on the success of the conversion
Sunrisas
+1  A: 

It would seem that this: http://www.kodefuguru.com/post/2010/06/24/TryParse-vs-Convert.aspx answers your question

fogedi
+1  A: 

Using TryParse would be the best option. Catching exception from convert method is expensive operation. Of course TryParse would only accepts strings while Convert.ToInt32 will take object and can perform conversions (unboxing, down-casting from long/double) apart from parsing.

VinayC
+1  A: 

To cover the ternary operator aspect of this question:

My advice on the use of ternary operators is not to use them if you aren't already so familiar with the code in question that it reads naturally to you. Concision makes the familiar more familiar and the strange, stranger.

When you've groked the discussion about TryParse here enough that you don't even need to think it through conciously anymore, the conversion from if-else to ?: will not just be trivial, it'll be automatic. Until then you're just going to add to your own confusion.

When I'm unfamiliar with something, I drop down to "baby-speak" code at first, learn the new thing, and then integrate it into my normal more concise style after.

Jon Hanna
Thanks for the advice Jon.
Popo