I don’t know how about you, but for me using int.TryParse() always feel somehow not right, resulting in an ugly three lines of code to do just one operation:
int value; if (!int.TryParse(valueToParseFromString, out value) value = 0;
If you are looking for cleaner code to satisfy your inner pedant you can use this one-line solution instead:
int value = int.TryParse(valueToParseFromString, out value) ? value : 0;
It will parse the valueToParseFromString and on success assign it to the value variable, otherwise it will return 0.
4 comments