Converting string to int or float got FormatException error

The code belows does not work:

int id = System.Convert.ToInt32(result.Attribute("ID").Value);

but the following code works fine:

int id;
int.TryParse(result.Attribute("ID").Value, out id);

Any ideas?

Thank you.

That is because there probably isn't a proper value in `result.Attribute("ID").Value` to make an integer out of, and TryParse swallows the FormatException for you invisibly since you're not handling the boolean it returns, which would've told you whether the conversion succeeded. :)

TryParse must set `id`, because the method marks that argument with the "out" keyword, but it sets it to 0 if the conversion failed. Is that what you get?