string str = "3.14159";
float fnum = float.Parse(str);
must have been googling wrong
string str = "3.14159";
float fnum;
bool result = float.TryParse(str, out fnum);
^ You could also wrap it up in a try/catch and catch the FormatException.
yes you could depends on your style of coding though I guess, I prefer the method I use but the guys in the office prefer the try catch method because it easier to see what's going on
Exceptions are fairly expencive, so I think its not only 'better looking' but more efficient to use tryparse.^ You could also wrap it up in a try/catch and catch the FormatException.
Exceptions are fairly expencive, so I think its not only 'better looking' but more efficient to use tryparse.
I've done my own tests and in situations where exceptions are thrown on a regular basis, the performance is terrible. If I remember my figures from a test (took a big file with ~10m piece of information - roughly 30% were not numbers, and recorded how long it took tryparse and exceptions to churn through it). The tryparse method was about 50x faster or somewhere abouts.While I agree that exceptions probably aren't the way to go here, I'd disagree that performance is a valid reason; exceptions are not as expensive as people think, and avoiding them for the sake of performance is almost always premature optimization. Have a read:
http://www.yoda.arachsys.com/csharp/exceptions2.html